1 最簡單的例子
#!/bin/bash
if [ 10 -lt 20 ]
then
echo "aaa"
else
echo "bbb"
fi
運行結果:
aaa
-lt 是 less than的縮寫。
2 shell script 中 if...else 的語法
if 某一判斷條件
then
...
elif 另一判斷條件
then
...
else
...
fi
再看一個稍微復雜一點的例子:
#!/bin/bash
echo "Please enter your age:"
read age
if [ -z "$age" ]
then
echo "Sorry, you didn't input."
elif [ "$age" -lt 20 ] || [ "$age" -ge 50 ]
then
echo "Sorry, you are out of the age range."
elif [ "$age" -ge 20 ] && [ "$age" -lt 30 ]
then
echo "You are in your 20s"
elif [ "$age" -ge 30 ] && [ "$age" -lt 40 ]
then
echo "You are in your 30s"
elif [ "$age" -ge 40 ] && [ "$age" -lt 50 ]
then
echo "You are in your 40s"
else
echo "Sorry, please input a number."
fi
運行:
Please enter your age:
43
You are in your 40s
3 判斷條件的寫法
常用的判斷條件有兩種寫法:
test 描述條件的表達式
or
[ 描述條件的表達式 ]
所以:
if [ -z "$age" ]
等于
if test -z "$age"
-z string 用于判斷一個字符串的長度是否為0。
當我們想知道一個判斷中的關鍵字,如 -z, -lt 或 -n 的含義時,我們可以使用命令:
man test
...
-n STRING
the length of STRING is nonzero
-z STRING
the length of STRING is zero
...
如果我們想把 if 和 then 寫在一行中,還可以這樣寫:
if [ -z "$age" ]
then
等于
if [ -z "$age" ]; then
最后,在Bash, Zsh and the Korn shell中,引入了一個功能更強大的關鍵字 [[ ]], 用來取代 [ ]。如果感興趣,可以看這里:http://mywiki.wooledge.org/BashFAQ/031
還有一種寫法:
# false && echo foo || echo bar
bar
# true || echo foo && echo bar
bar
其中&&為真時執(zhí)行,||為假時執(zhí)行。