1. 程式人生 > >linux中shell if 判斷總結

linux中shell if 判斷總結

UNIX Shell 裡面比較字元寫法

-eq     等於;              -ne    不等於;

-gt    大於;             -lt    小於 ;

-le    小於等於;       -ge   大於等於;

-z    空串;                   -n    非空串;

=    兩個字元相等;     !=    兩個字元不等

無論什麼程式語言都離不開條件判斷。SHELL也不例外。

大體的格式如下:

if list then
do something here
elif list then
do another thing here
else
do something else here
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)指定的裝置為終端時為真

4 複雜邏輯判斷

-a        與
-o       或
!       非

語法雖然簡單,但是在SHELL裡使用的時候,它可以實現強大的功能或執行邏輯。