標籤:
無論什麼程式設計語言都離不開條件判斷。SHELL也不例外。
大體的格式如下:
if list then
do something here
elif list then
do another thing here
else
do something else here
fi
一個例子:
#!/bin/sh
SYSTEM=`uname -s` # 擷取作業系統類型,我本地是linux
if [ $SYSTEM = "Linux" ] ; then # 如果是linux話輸出linux字串
echo "Linux"
elif [ $SYSTEM = "FreeBSD" ] ; then
echo "FreeBSD"
elif [ $SYSTEM = "Solaris" ] ; then
echo "Solaris"
else
echo "What?"
fi # 判斷結束,以fi結尾
基本上和其他指令碼語言一樣。沒有太大區別。不過值得注意的是。[]裡面的條件判斷。說明如下:
1 字串判斷
str1 = str2 當兩個串有相同內容、長度時為真
str1 != str2 當串str1和str2不等時為真
-n str1 當串的長度大於0時為真(串非空)
-z str1 當串的長度為0時為真(空串)
str1 當串str1為非空時為真
2 數位判斷
int1 -eq int2 兩數相等為真
int1 -ne int2 兩數不等為真
int1 -gt int2 int1大於int2為真
int1 -ge int2 int1大於等於int2為真
int1 -lt int2 int1小於int2為真
int1 -le int2 int1小於等於int2為真
3 檔案相關的if判斷條件陳述式
-r file 使用者可讀為真
-w file 使用者可寫為真
-x file 使用者可執行為真
-f file 檔案為正規檔案為真
-d file 檔案為目錄為真
-c file 檔案為字元特殊檔案為真
-b file 檔案為塊特殊檔案為真
-s file 檔案大小非0時為真
-t file 當檔案描述符(預設為1)指定的裝置為終端時為真
3 複雜邏輯判斷
-a 與
-o 或
! 非
文法雖然簡單,但是在SHELL裡使用的時候,它可以實現強大的功能或執行邏輯。
Linux shell if判斷語句