天天看點

shell中的條件判斷

利用test指令來實作條件判斷,而不是利用command的傳回值

1.有兩種模式:

  1. test指令
if test condition
then
    commands
fi
           
  1. 中括号[]代替test
if [condition]
then
    commands
fi
           

其中的condition也可以是複合的條件判斷

#與
[condition1]&&[condition2]
#或
[condition1]||[condition2]
           
  1. test 支援三類條件:
#1.**數值比較**


#test 整數1 –eq 整數2                    整數相等
#test 整數 1 –ge 整數2                   整數1大于等于整數2
#test 整數1 –gt 整數 2                   整數1大于整數2
#test 整數1 –le 整數 2                   整數1小于等于整數2
#test 整數1 –lt 整數 2                   整數1小于整數2
#test 整數1 –ne 整數 2                   整數1不等于整數2

if [  -eq  ]
then
        echo "1 is equal to 2"
else
        echo "1 is not equal to 2"
fi
#2.字元串比較
#test –n 字元串                       字元串的長度非零
#test –z 字元串                       字元串的長度為零
#test 字元串1 = 字元串 2              字元串相等
#test 字元串1 !=字元串2               字元串不等
#注意< >要用轉義符号
if [ $str1 \> $str2]
then 
    echo "$str1 > $str2"
else
    echo "$str1 <= $str2"
fi
#if 後面還可以進行這樣的比較
#判斷str長度是否為非0
if [ -n "$str" ]
#判斷str長度是否為為0
if [ -z "$str" ]
#有點小懶,就不舉例了,嘿嘿

#3.檔案比較
#test  File1 –ef  File2  兩個檔案具有同樣的裝置号和i結點号
#test  File1 –nt  File2  檔案1比檔案2 新
#test  File1 –ot  File2  檔案1比檔案2 舊
#test –b File            檔案存在并且是塊裝置檔案
#test –c File            檔案存在并且是字元裝置檔案
#test –d File            檔案存在并且是目錄
#test –e File            檔案存在
#test –f File            檔案存在并且是正規檔案
#test –g File            檔案存在并且是設定了組ID
#test –G File            檔案存在并且屬于有效組ID
#test –h File            檔案存在并且是一個符号連結(同-L)
#test –k File             檔案存在并且設定了sticky位
#test –b File            檔案存在并且是塊裝置檔案
#test –L File            檔案存在并且是一個符号連結(同-h)
#test –o File            檔案存在并且屬于有效使用者ID
#test –p File            檔案存在并且是一個命名管道
#test –r File            檔案存在并且可讀
#test –s File            檔案存在并且是一個套接字
#test –t FD               檔案描述符是在一個終端打開的
#test –u File           檔案存在并且設定了它的set-user-id位
#test –w File            檔案存在并且可寫
#test –x File            檔案存在并且可執行
if [ -d / ]
then 
    echo " / is a directory "
else
    echo " / is not a directory "
fi
           

ps:關于檔案的各種操作有很多,就不一一列舉了