2010-03-01 56 views
33

我不知道如何在shell中使用多個測試執行if。我無法寫這個劇本:如果在shell腳本中使用elif fi

./compare.sh:::缺少`]

echo "You have provided the following arguments $arg1 $arg2 $arg3" 
if [ "$arg1" = "$arg2" && "$arg1" != "$arg3" ] 
then 
    echo "Two of the provided args are equal." 
    exit 3 
elif [ $arg1 = $arg2 && $arg1 = $arg3 ] 
then 
    echo "All of the specified args are equal" 
    exit 0 
else 
    echo "All of the specified args are different" 
    exit 4 
fi 

問題是每次我得到這個錯誤沒有找到」命令

+5

很多評論家建議你使用[[而不是[但是這會讓你的腳本特定於bash。如果您可以堅持使用普通的Bourne shell(sh)語法,那麼您將減少維護和可移植性問題。 –

回答

25

sh被解釋&&作爲外殼運營商。將其更改爲-a,這是[的聯合運營:

[ "$arg1" = "$arg2" -a "$arg1" != "$arg3" ] 

此外,你應該總是引用變量,因爲[當你離開過爭論變得混亂。

5

將「[」更改爲「[[」和「]」爲「]]」。

+1

更好的是,將'[''更改爲'test' –

7

使用雙括號...

if [[ expression ]]

+1

注意,這是一個解決方案,因爲'[[''構建內置在shell中,而'['是'test'命令的另一個名稱,因此受到它的語法 - 參見'man test' –

+4

從技術上講,'['是shell內建的,但'[['是shell關鍵字。這是不同的。 –

+1

所以看到bash命令的結果'type [','type [[','help ['和'help [['。 – Apostle

2

我有你的代碼示例。試試這個:

echo "*Select Option:*" 
echo "1 - script1" 
echo "2 - script2" 
echo "3 - script3 " 
read option 
echo "You have selected" $option"." 
if [ $option="1" ] 
then 
    echo "1" 
elif [ $option="2" ] 
then 
    echo "2" 
    exit 0 
elif [ $option="3" ] 
then 
    echo "3" 
    exit 0 
else 
    echo "Please try again from given options only." 
fi 

這應該有效。 :)

+0

這個文件對我來說很古怪。爲什麼在'else'之後沒有'then'? 它實際上可能不是古怪的,但這是它看起來的樣子,相比於C。 – Rolf

+0

空間是在$ option和before之後需要運行它,否則每次都是1 – PiyusG

23

喬希李的回答工作,但你可以使用「& &」運營商這樣更好的可讀性:

echo "You have provided the following arguments $arg1 $arg2 $arg3" 
if [ "$arg1" = "$arg2" ] && [ "$arg1" != "$arg3" ] 
then 
    echo "Two of the provided args are equal." 
    exit 3 
elif [ $arg1 = $arg2 ] && [ $arg1 = $arg3 ] 
then 
    echo "All of the specified args are equal" 
    exit 0 
else 
    echo "All of the specified args are different" 
    exit 4 
fi 
1

這是爲我工作,

# cat checking.sh 
#!/bin/bash 
echo "You have provided the following arguments $arg1 $arg2 $arg3" 
if [ "$arg1" = "$arg2" ] && [ "$arg1" != "$arg3" ] 
then 
    echo "Two of the provided args are equal." 
    exit 3 
elif [ $arg1 == $arg2 ] && [ $arg1 = $arg3 ] 
then 
    echo "All of the specified args are equal" 
    exit 0 
else 
    echo "All of the specified args are different" 
    exit 4 
fi 

# ./checking.sh 
You have provided the following arguments 
All of the specified args are equal 

您可以添加「set -x」腳本來排除錯誤,

謝謝。