2012-08-30 206 views
3

我學習bash和希望你們能幫助我發生了什麼事情與下面的腳本bash腳本給出錯誤的輸出

#!/bin/bash 

#primer if 
if [ -f $file1 ]; then 
     echo "file1 is a file" 
else 
     echo "file1 is not a regular file" 
fi 
#segundo if 
if [ -r $file1 ]; then 
     echo "file1 has read permission" 
else 
    echo "file1 doesnot have read permission" 
fi 
#tercer if 
if [ -w $file1 ]; then 
     echo "file1 has write permission" 
else 
    echo "file1 doesnot have write permission" 
fi 
#cuarto if 
if [ -x $file1 ]; then 
     echo "file1 has execute permission" 
else 
    echo "file1 doesnot have execute permission" 
fi 

它看起來對我說,如果我改變了也沒關係文件的權限,因爲輸出始終是相同的

[email protected]:~/Books/2012/ubuntu_unleashed$ ./script.sh 
file1 is a file 
file1 has read permission 
file1 has write permission 
file1 has execute permission 
[email protected]:~/Books/2012/ubuntu_unleashed$ ll file1 
-rw-r--r-- 1 fmp fmp 0 Aug 30 13:21 file1 
[email protected]:~/Books/2012/ubuntu_unleashed$ chmod 200 file1 
[email protected]:~/Books/2012/ubuntu_unleashed$ ./script.sh 
file1 is a file 
file1 has read permission 
file1 has write permission 
file1 has execute permission 
[email protected]:~/Books/2012/ubuntu_unleashed$ ll file1 
--w------- 1 fmp fmp 0 Aug 30 13:21 file1 
[email protected]:~/Books/2012/ubuntu_unleashed$ chmod 000 file1 
[email protected]:~/Books/2012/ubuntu_unleashed$ ll file1 
---------- 1 fmp fmp 0 Aug 30 13:21 file1 
[email protected]:~/Books/2012/ubuntu_unleashed$ ./script.sh 
file1 is a file 
file1 has read permission 
file1 has write permission 
file1 has execute permission 

文件1可以爲空或不是靜態輸出是一樣的,做同樣的測試

任何人能向我解釋什麼是wron G?

感謝

BTW這裏的腳本是compare3 Ubuntu的解開了書2011版(圖書網站http://ubuntuunleashed.com/)的233頁上的修改版本

回答

4

file1變量是不確定的。

你應該添加在你的腳本的開頭file1="file1"

2

更改爲$1$file1變量或添加在腳本的開頭如下(將#後/斌/慶典!):

set file1=$1 

所以,你可以調用你的腳本是這樣的:

./script.sh file 
+0

設置僅用於tcsh還是bash? – murpholinox

+0

是的,'set'它也可以在bash中使用 – higuaro

2

或刪除DOLAR標誌,或更換$file1$1並使用腳本./script.sh file1

3

這是所有測試都成功的原因:自變量爲空,你會得到

if [ -f ]; ... 
if [ -r ]; ... 
if [ -w ]; ... 
if [ -x ]; ... 

因爲你使用單支架,慶典只看到一個測試條件的單個詞。當測試命令只看到一個參數時,如果該單詞不是空的,則結果爲真,並且在每種情況下,該單詞包含2個字符。

當然,修正是聲明變量。此外,您應該使用bash的條件結構

if [[ -f $file ]]; ... 
if [[ -r $file ]]; ... 
if [[ -w $file ]]; ... 
if [[ -x $file ]]; ... 

當雙支架使用,bash將看到的情況2分的話,即使變量爲空或空。