Shell中的條件判斷語句是前面一篇“Shell中的條件測試語句”的更新篇,也就是說,前面的測試語句是為了現在的判斷語句if~then~fi語句服務的。
我們還是按照注意點和代碼實作的方式鋪開:
1)基本的if-then-fi語句可以用來判斷基本的單層的分支結構,其形式如下:
其中if後面的測試語句一般都使用[]指令來做。如下面的例子:
<span style="font-size:14px;">#-----------------------------/chapter4/ex4-18.sh------------------
#! /bin/sh
#使用條件測試判斷/bin/bash是否是一個正常檔案
if [ -f /bin/bash ]; then
echo "/bin/bash is a file"
fi
</span>
2)if-then-else-fi語句可以處理兩層的分支判斷語句。如下:
<span style="font-size:14px;">#-----------------------------/chapter4/ex4-22.sh------------------
#! /bin/sh
#輸出提示資訊
echo "Please enter a number:"
#從鍵盤讀取使用者輸入的數字
read num
#如果使用者輸入的數字大于10
if [ "$num" -gt 10 ]; then
#輸出大于10的提示資訊
echo "The number is greater than 10."
#否則
else
#輸出小于或者等于10的提示資訊
echo "The number is equal to or less than 10."
fi
</span>
3)if-then-elif-then-elif-then-...-else-fi。這種語句可以實作多重判斷,注意最後一定要以一個else結尾。如下:
<span style="font-size:14px;">#-----------------------------/chapter4/ex4-24.sh------------------
#! /bin/sh
echo "Please enter a score:"
read score
if [ -z "$score" ]; then
echo "You enter nothing.Please enter a score:"
read score
else
if [ "$score" -lt 0 -o "$score" -gt 100 ]; then
echo "The score should be between 0 and 100.Please enter again:"
read score
else
#如果成績大于90
if [ "$score" -ge 90 ]; then
echo "The grade is A."
#如果成績大于80且小于90
elif [ "$score" -ge 80 ]; then
echo "The grade is B."
#如果成績大于70且小于80
elif [ "$score" -ge 70 ]; then
echo "The grade is C."
#如果成績大于60且小于70
elif [ "$score" -ge 60 ]; then
echo "The grade is D."
#如果成績小于60
else
echo "The grade is E."
fi
fi
fi
</span>
4)要退出程式的時候,可以使用exit status語句。退出的狀态status為0的時候,意味着腳本成功運作結束;非0表示程式執行過程出現某些錯誤,不同的錯誤對應着不同的退出狀态。盡管使用者可以自定義程式中的退出狀态status,但是通常情況下每個status都有特定的含義,是以在自定義傳回status的時候,一定要避免造成歧義。例子如下:
<span style="font-size:14px;">01 #-----------------------------/chapter4/ex4-26.sh------------------
02 #! /bin/sh
03
04 #如果檔案已經存在,則直接退出,檔案名時輸入的第一個參數
05 if [ -e "$1" ]
06 then
07 echo "file $1 exists."
08 exit 1
09 #如果檔案不存在,則建立檔案,使用touch來建立檔案,也可以使用重定向來建立檔案echo "Hello~" > ./test.log 即在目前目錄下建立一個test.log檔案
10 else
11 touch "$1"
12 echo "file $1 has been created."
13 exit 0
14 fi
</span>
5)case-esac語句實作多重條件判斷。如下:
注意:每一個變量内容的程式段最後都需要兩個分号 (;;) 來代表該程式段落的結束;每個變量情況最後都要有)結尾;其餘情況用*)來表示;最後要用esac來結束,即case反過來。
<span style="font-size:14px;">#-----------------------------/chapter4/ex4-27.sh------------------
#! /bin/sh
#輸出提示資訊
echo "Hit a key,then hit return."
#讀取使用者按下的鍵
read keypress
#case語句開始
case "$keypress" in
#小寫字母
[[:lower:]])
echo "Lowercase letter.";;
#大寫字母
[[:upper:]])
echo "Uppercase letter.";;
#單個數字
[0-9])
echo "Digit.";;
#其他字元
*)
echo "other letter.";;
esac
</span>
參考:
《鳥哥的Linux私房菜》
《Shell從入門到精通》