Shell中的條件判斷語句if~then~fi


    Shell中的條件判斷語句是前面一篇“Shell中的條件測試語句”的升級篇,也就是說,前面的測試語句是爲了現在的判斷語句if~then~fi語句服務的。

    我們還是按照注意點和代碼實現的方式鋪開:

    

    1)基本的if-then-fi語句可以用來判斷基本的單層的分支結構,其形式如下:

其中if後面的測試語句一般都使用[]命令來做。如下面的例子:

<span style="font-size:14px;">#-----------------------------/chapter4/ex4-18.sh------------------
#! /bin/sh
#使用條件測試判斷/bin/bash是否是一個常規文件
if [ -f /bin/bash ]; then 
	echo "/bin/bash is a file"
fi
</span>

    2)if-then-else-fi語句可以處理兩層的分支判斷語句。如下:


<span style="font-size:14px;">#-----------------------------/chapter4/ex4-22.sh------------------
#! /bin/sh

#輸出提示信息
echo "Please enter a number:"
#從鍵盤讀取用戶輸入的數字
read num
#如果用戶輸入的數字大於10
if [ "$num" -gt 10 ]; then
		#輸出大於10的提示信息
 	echo "The number is greater than 10."
#否則
else
	#輸出小於或者等於10的提示信息
		echo "The number is equal to or less than 10."
fi
</span>


    3)if-then-elif-then-elif-then-...-else-fi。這種語句可以實現多重判斷,注意最後一定要以一個else結尾。如下:


<span style="font-size:14px;">#-----------------------------/chapter4/ex4-24.sh------------------
#! /bin/sh

echo "Please enter a score:"

read score

if [ -z "$score" ]; then
   echo "You enter nothing.Please enter a score:"
   read score
else
   if [ "$score" -lt 0 -o "$score" -gt 100 ]; then
      echo "The score should be between 0 and 100.Please enter again:"
      read score
   else
      #如果成績大於90
      if [ "$score" -ge 90 ]; then
         echo "The grade is A."
      #如果成績大於80且小於90
      elif [ "$score" -ge 80 ]; then
         echo "The grade is B."
      #如果成績大於70且小於80
      elif [ "$score" -ge 70 ]; then
         echo "The grade is C."
      #如果成績大於60且小於70
      elif [ "$score" -ge 60 ]; then
         echo "The grade is D."
      #如果成績小於60
      else
         echo "The grade is E."
      fi
   fi
fi
</span>

    4)要退出程序的時候,可以使用exit status語句。退出的狀態status爲0的時候,意味着腳本成功運行結束;非0表示程序執行過程出現某些錯誤,不同的錯誤對應着不同的退出狀態。儘管用戶可以自定義程序中的退出狀態status,但是通常情況下每個status都有特定的含義,因此在自定義返回status的時候,一定要避免造成歧義。例子如下:

<span style="font-size:14px;">01   #-----------------------------/chapter4/ex4-26.sh------------------
02   #! /bin/sh
03   
04   #如果文件已經存在,則直接退出,文件名時輸入的第一個參數
05   if [ -e "$1" ]
06   then
07      echo "file $1 exists."
08      exit 1
09   #如果文件不存在,則創建文件,使用touch來創建文件,也可以使用重定向來創建文件echo "Hello~" > ./test.log  即在當前目錄下新建一個test.log文件
10   else
11      touch "$1"
12      echo "file $1 has been created."
13      exit 0
14   fi
</span>

    5)case-esac語句實現多重條件判斷。如下:


    注意:每一個變量內容的程序段最後都需要兩個分號 (;;) 來代表該程序段落的結束;每個變量情況最後都要有)結尾;其餘情況用*)來表示;最後要用esac來結束,即case反過來。

<span style="font-size:14px;">#-----------------------------/chapter4/ex4-27.sh------------------
#! /bin/sh

#輸出提示信息
echo "Hit a key,then hit return."
#讀取用戶按下的鍵
read keypress
#case語句開始
case "$keypress" in
   #小寫字母
   [[:lower:]])
      echo "Lowercase letter.";;
   #大寫字母
   [[:upper:]])
      echo "Uppercase letter.";;
   #單個數字
   [0-9])
      echo "Digit.";;
   #其他字符
   *)
      echo "other letter.";;
esac
</span>


    參考:

    《鳥哥的Linux私房菜》

    《Shell從入門到精通》



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章