最近在寫腳本用到了if test去測試或者判斷,發現裡邊東西挺多的,撿幾個個人用到的寫一下
if test 可以測試三種 字元 數字 檔案
字元串比較 != 和 = 沒有“==”符号
數字 -lt -gt -ne -le -ge 沒有“>、<”符号
如果x=04 y=4 這樣的測試會不一樣的結果
if [ $x = $y ]與 if [ $x -ne $y ]為什麼你肯定猜到了
測試比較 -z 測試是否是0個字元 -n 測試字元是否不為空
&& 如果是“前面”,則“後面”
[ -f /var/run/dhcpd.pid ] && rm /var/run/dhcpd.pid 檢查 檔案是否存在,如果存在就删掉
|| 如果不是“前面”,則後面
[ -f /usr/sbin/dhcpd ] || exit 0 檢驗檔案是否存在,如果存在就退出
以上這兩個是比較實用簡單的寫法
另外需要注意字元串比較的時候$String 一定要用引号引起來去比較:"$String" = "abc"for
好多人會碰到 sh: test:argument expected 就是因為變量為null然後進行比對了
第二注意就是[] 這個兩邊都要有空格,否則也會報錯
傳統if 從句子——以條件表達式作為
if條件
if [ 條件表達式 ]then
command
else
fi
條件表達式如下
檔案表達式
if [ -f file ] 如果檔案存在
if [ -d ... ] 如果目錄存在
if [ -s file ] 如果檔案存在且非空
if [ -r file ] 如果檔案存在且可讀
if [ -w file ] 如果檔案存在且可寫
if [ -x file ] 如果檔案存在且可執行
整數變量表達式
if [ int1 -eq int2 ] 如果int1等于int2
if [ int1 -ne int2 ] 如果不等于
if [ int1 -ge int2 ] 如果>=
if [ int1 -gt int2 ] 如果>
if [ int1 -le int2 ] 如果<=
if [ int1 -lt int2 ] 如果<
字元串變量表達式
If [ $a = $b ] 如果string1等于string2
字元串允許使用指派号做等号
if [ $string1 != $string2 ] 如果string1不等于string2
if [ -n $string ] 如果string 非空(非0),傳回0(true)
if [ -z $string ] 如果string 為空
if [ $sting ] 如果string 非空,傳回0 (和-n類似)
本文轉自 aklaus 51CTO部落格,原文連結:http://blog.51cto.com/aklaus/1766413