Linux中的if語句根據(jù)其后緊跟的command語句的退出碼是否非零進(jìn)行邏輯判斷偷厦,這是不同于其他編程語言的一個(gè)特性。
狀態(tài)退出碼的介紹可以參考:http://www.reibang.com/p/ba478a2dbcbc
if-then語句的基本格式
if command
then
? ? commands
fi
抑或是:
if?command淮阐;?then
commands
fi
請(qǐng)注意后者在待求值的命令尾部增加了分號(hào)
if-then-else語句的基本格式
if command
then?
????commands
else
????commands
fi
需要多個(gè)if判斷邏輯時(shí)使用如下命令
if command1
then
? ??commands set 1
elif command2
then
? ??commands set 2
else?
????commands?set 3
fi
test命令
在if-then語句中需要以命令是否成立作為判斷條件時(shí)用test命令來輔助。
語法:
1.test condition
test命令中的條件成立,test命令將退出并返回狀態(tài)碼0印蔬,反之原押,退出返回非零狀態(tài)碼。
當(dāng)test命令中的語句為空時(shí)帮碰,會(huì)判定為語句不成立代兵,退出并返回非零狀態(tài)碼尼酿。
2.[ condition ]
bash shell 提供了另一種測(cè)試方法,也就是test命令的另一種語法植影。
在if-then語句中將是這樣的形態(tài):
if [ condition ]
then?
? ? commands
fi
test命令可以判斷的三類條件
□數(shù)值比較
□字符串比較
□文件比較
數(shù)值比較
????符 號(hào)? ? ? ? ? ? ? ? 描述
? n1 -eq n2? ? ? ? n1與n2是否相等
? n1 -ge n2? ? ? ? n1是否大于或等于n2
? n1 -gt n2? ? ? ? ?n1是否大于n2
? n1 -le n2? ? ? ? ?n1是否小于或等于n2
? n1 -lt n2? ? ? ? ? n1是否小于n2
? n1 -ne n2? ? ? ? n1是否不等于n2
這里能處理的是整數(shù)和變量:
#!/bin/bash
value1=10
if [ $value1 -gt 5 ]
then
? ?echo "The test value $value1 is greater than 5"
else
? ?echo "The test value $value1 is smaller than 5"
不能處理浮點(diǎn)數(shù)裳擎。
字符串比較
????符 號(hào)? ? ? ? ????????描述
? str1 = str2? ? ? ? str1是否與str2相同
? str1 != str2? ? ? ? str1是否與str2不同
? str1 < str2? ? ? ? ?str1是否比str2小
? str1 > str2? ? ? ? ?str1是否比str2大
? ? -n str1? ? ? ? ? ? ?str1長度是否非零
? ? -z str1? ? ? ? ? ? ?str1長度是否為0
文件比較
符號(hào) 描述
-d file? ? ? file是否為一個(gè)目錄
-e file? ? ? file是否存在
-f file? ? ? file是否存在并是一個(gè)文件
-r file? ? ? file是否存在并可讀
-s file? ? ? file是否存在并非空
-w file? ? ? file是否存在并可寫
-x file? ? ? file是否存在并可執(zhí)行
-O file? ? ? file是否存在并屬當(dāng)前用戶所有
-G file? ? ? file是否存在并且默認(rèn)組與當(dāng)前用戶相同
file1 -nt file1? file1是否比file2新
file1 -ot file1? file1是否比file2舊? ? #這里的新舊依據(jù)是文件的創(chuàng)建時(shí)間
歡迎指正和補(bǔ)充。