Shell 有三種 if … else 語句:
if ... fi 語句;
if ... else ... fi 語句;
if ... elif ... else ... fi 語句。
三個分別相當於:
if
if….else
if….else if….else
1、if … fi 語句語法
if [ expression ]
then
Statement(s) to be executed if expression is true
fi
注意:
- 如果 expression 返回 true,then 後邊的語句將會被執行;如果返回 false,不會執行任何語句。
- 最後必須以 fi 來結尾閉合 if,fi 就是 if 倒過來拼寫。
- expression 和方括號([ ])之間必須有空格,否則會有語法錯誤。
舉例:
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
fi
if [ $a != $b ]
then
echo "a is not equal to b"
fi
運行結果:
a is not equal to b
2、if … else … fi 語句的語法
if [ expression ]
then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is not true
fi
如果 expression 返回 true,那麼 then 後邊的語句將會被執行;否則,執行 else 後邊的語句。
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
執行結果:
a is not equal to b
3、if … elif … fi 語句
if … elif … fi 語句可以對多個條件進行判斷,語法爲:
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi
哪一個 expression 的值爲 true,就執行哪個 expression 後面的語句;如果都爲 false,那麼不執行任何語句。
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
elif [ $a -lt $b ]
then
echo "a is less than b"
else
echo "None of the condition met"
fi
運行結果:
a is less than b
4、其他用法
if … else 語句也可以寫成一行,以命令的方式來運行,像這樣:
if test $[2*3] -eq $[1+5]; then echo 'The two numbers are equal!'; fi;
if … else 語句也經常與 test 命令結合使用,如下所示:
num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
echo 'The two numbers are equal!'
else
echo 'The two numbers are not equal!'
fi
輸出:
The two numbers are equal!