注意1: if 表達式和case 表達式的區別及什么時候使用哪個要有明確的區分?
『 if .... then .... fi 』對于變量的判斷是以『比對』的方式來分辨的, 如果符合狀態就進行某些行為,并且透過較多層次 (就是elif ) 的方式來進行多個變量的程序代碼撰寫(針對性不強,范圍大的時候使用)。
『?case ... in .... esac』 使用在變量的內容已經既定,就只有幾個選擇的時候使用(具有很強的正對性);
注意1:腳本中,變量的下達方式是怎么樣的呢?
直接下達方式: 在執行腳本的時候后面加上參數($1,$2......) ? 如: ./xx.sh 參數1 參數2 .....
交互式下達方式:通過 read 這個指令來讓用戶輸入變量的內容。?
?
一『 if .... then .... fi 』的使用基本方法
1、單一的條件判斷式:
語法:
if [ 條件判斷式 ]; then當條件判斷式成立時,可以進行的指令工作內容; fi //將if反過來寫,就是結束if之意!
&& 代表 AND?
|| 代表 or?
forexample:
#!/bin/bash set -x //進行查錯功能 #program; # This program shows the user's choice #History: #2017/06/21 likui First release PATH=/bin:/sbin:/uer/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/bin export PATH read -p "Please input (Y/y)" yn if [ "$yn" == "Y" ] || [ "$yn" = "y" ]; then echo "OK,continue" //if 和 if 之間添加我們需要的代碼 exit 0 fi if [ "$yn" == "N" ] || [ "$yn" == "n" ]; then echo "Oh,interrupt!" exit 0 fi echo "I don't know what your choice is "
?
2、多重、復雜條件判斷式
語法1:
# 一個條件判斷,分成功進行與失敗進行 (else)
if [ 條件判斷式 ]; then當條件判斷式成立時,可以進行的指令工作內容 else當條件判斷式不成立時,可以進行的指令工作內容 fi
語法2:
# 多個條件判斷 (if ... elif ... elif ... else) 分多種不同情況執行
if [ 條件判斷式一 ]; then當條件判斷式一成立時,可以進行的指令工作內容 elif [ 條件判斷式二 ]; then當條件判斷式二成立時,可以進行的指令工作內容 else當條件判斷式一與二均不成立時,可以進行的指令工作內容; fi
forexample1:
forexample2:
forexample3:
#!/bin/bash # Program: # You input your demobilization date, I calculate how many days # before you demobilize. # History: # 2005/08/29 VBird First release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~ /bin export PATH # 1. 告知用戶這支程序的用途,并且告知應該如何輸入日期格式? echo "This program will try to calculate :" echo "How many days before your demobilization date..." read -p "Please input your demobilization date (YYYYMMDD ex>20090401): " date2 # 2. 測試一下,這個輸入的內容是否正確?利用正規表示法啰~ date_d=$(echo $date2 |grep '[0-9]\{8\}') # 看看是否有八個數字 if [ "$date_d" == "" ]; then echo "You input the wrong date format...." exit 1 fi # 3. 開始計算日期啰~ declare -i date_dem=`date --date="$date2" +%s` # 退伍日期秒數 declare -i date_now=`date +%s` # 現在日期秒數 declare -i date_total_s=$(($date_dem-$date_now)) # 剩余秒數統計 declare -i date_d=$(($date_total_s/60/60/24)) # 轉為日數 if [ "$date_total_s" -lt "0" ]; then # 判斷是否已退伍 echo "You had been demobilization before: " $((-1*$date_d)) " ago" else declare -i date_h=$(($(($date_total_s-$date_d*60*60*24))/60/60)) echo "You will demobilize after $date_d days and $date_h hours." fi
?
二、『?case ... in .... esac』的基本用法:
1、單一的case條件判斷式:
基礎語法:
case $變量名稱 in //關鍵詞為 case ,還有變數前有錢字號"第一個變量內容") //每個變量內容建議用雙引號括起來,關鍵詞則為小括號 )程序段;; //每個類別結尾使用兩個連續的"第二個變量內容")程序段;;*) //最后一個變量內容都會用 * 程序段 //來代表所有其他值不包含第一個變量內容與第二個變量內容的其他程序執行段;; esac
forexample:
forexample2: ? 變量的2種下達方式的程序代碼
?
?
?