1. 程式人生 > >shell編程學習筆記(八):Shell中if判斷的使用

shell編程學習筆記(八):Shell中if判斷的使用

空格 score 相等 span shell編程 str2 != color font

一、if的語法:

1、單分支語句結構

if [ 條件表達式 ]; then
    指令 
fi

2、雙分支語句結構

if [ 條件表達式 ]; then 
    指令一 
else 
    指令二 
fi

3、多分支語句結構

if [ 條件表達式 ]; then
   指令一
elif [ 條件表達式 ]; then
   指令二
else
   指令三
fi

上面直接給出了多分支if語句的一個實例。從上面三個結構中可以看出,條件表達式的左右都要有空格

二、條件表達式的內容

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、文件的判斷

-r file     用戶可讀為真 
-w file     用戶可寫為真 
-x file     用戶可執行為真 
-f file     文件為正規文件為真 
-d file     文件為目錄為真 
-c file     文件為字符特殊文件為真 
-b file     文件為塊特殊文件為真 
-s file     文件大小非0時為真 
-t file     當文件描述符(默認為1)指定的設備為終端時為真

4、復雜邏輯判斷

條件表達式中可能有多個條件,需要使用與或非等邏輯操作。

-a         與 
-o        或 
!        非

三、實例

if [ $score -ge 0 ]&&[ $score -lt 60 ];then
        echo "sorry,you are lost!"
elif [ $score -ge 60 ]&&[ $score -lt 85 ];then
        echo "just soso!"
elif [ $score -le 100 ]&&[ $score -ge 85 ];then
        echo "good job!"
else
        echo "input score is wrong , the range is [0-100]!"
fi

當然,上面的實例也可以用 -a 來改寫:

if [ $score -ge 0 -a $score -lt 60 ];then
        echo "sorry,you are lost!"
elif [ $score -ge 60 -a $score -lt 85 ];then
        echo "just soso!"
elif [ $score -le 100 -a $score -ge 85 ];then
        echo "good job!"
else
        echo "input score is wrong , the range is [0-100]!"
fi

shell編程學習筆記(八):Shell中if判斷的使用