Linux Shell腳本if-else語句及test命令

Linux中的if語句根據(jù)其后緊跟的command語句的退出碼是否非零進行邏輯判斷,這是不同于其他編程語言的一個特性。

狀態(tài)退出碼的介紹可以參考:http://www.itdecent.cn/p/ba478a2dbcbc

if-then語句的基本格式

if command

then

? ? commands

fi

抑或是:

if?command;?then

commands

fi

請注意后者在待求值的命令尾部增加了分號

if-then-else語句的基本格式

if command

then?

????commands

else

????commands

fi

需要多個if判斷邏輯時使用如下命令

if command1

then

? ??commands set 1

elif command2

then

? ??commands set 2

else?

????commands?set 3

fi

test命令

在if-then語句中需要以命令是否成立作為判斷條件時用test命令來輔助。

語法:

1.test condition

test命令中的條件成立,test命令將退出并返回狀態(tài)碼0,反之,退出返回非零狀態(tài)碼。

當(dāng)test命令中的語句為空時,會判定為語句不成立,退出并返回非零狀態(tài)碼。

2.[ condition ]

bash shell 提供了另一種測試方法,也就是test命令的另一種語法。

在if-then語句中將是這樣的形態(tài):

if [ condition ]

then?

? ? commands

fi


test命令可以判斷的三類條件

□數(shù)值比較

□字符串比較

□文件比較

數(shù)值比較

????符 號? ? ? ? ? ? ? ? 描述

? 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"

不能處理浮點數(shù)。

字符串比較

????符 號? ? ? ? ????????描述

? str1 = str2? ? ? ? str1是否與str2相同

? str1 != str2? ? ? ? str1是否與str2不同

? str1 < str2? ? ? ? ?str1是否比str2小

? str1 > str2? ? ? ? ?str1是否比str2大

? ? -n str1? ? ? ? ? ? ?str1長度是否非零

? ? -z str1? ? ? ? ? ? ?str1長度是否為0


文件比較

符號 描述

-d file? ? ? file是否為一個目錄

-e file? ? ? file是否存在

-f file? ? ? file是否存在并是一個文件

-r file? ? ? file是否存在并可讀

-s file? ? ? file是否存在并非空

-w file? ? ? file是否存在并可寫

-x file? ? ? file是否存在并可執(zhí)行

-O file? ? ? file是否存在并屬當(dāng)前用戶所有

-G file? ? ? file是否存在并且默認組與當(dāng)前用戶相同

file1 -nt file1? file1是否比file2新

file1 -ot file1? file1是否比file2舊? ? #這里的新舊依據(jù)是文件的創(chuàng)建時間

歡迎指正和補充。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容