標籤:
1. 指令碼判斷命令輸出是否為空白
(1)判斷字串為空白
if [ "$str" = "" ]
if [ x"$str" = x ]
if [ -z "$str" ] (-n 為非空)
注意:都要代雙引號,否則有些命令會報錯,養成好習慣吧!
2.輸入y/n
可以使用判斷符號進行資料的判斷,如檢查某變數是否為空白 [ -z $SHELL ],需要注意的是中括弧(“[]”)內的組件必須以空格隔開。有以下指令碼:
#!/bin/bashread -p "input you choice(y/n):" choice[ "$choice" == "y" ] || [ "$choice" == "Y" ] && echo "OK,continue" && exit 0[ "$choice" == "n" ] || [ "$choice" == "N" ] && echo "Oh,interrupt!" && exit 0echo "I don‘t know what is your choice" && exit 0
#! /bin/shecho "Is it morning? Please answer yes or no."read YES_OR_NOif [ "$YES_OR_NO" = "yes" ]; then echo "Good morning!"elif [ "$YES_OR_NO" = "no" ]; then echo "Good afternoon!"else echo "Sorry, $YES_OR_NO not recognized. Enter yes or no." exit 1fiexit 0
(3)while條件迴圈
和C語言類似。比如一個驗證密碼的指令碼:#! /bin/shecho "Enter password:"read TRYwhile [ "$TRY" != "secret" ]; do echo "Sorry, try again" read TRYdone下面的例子通過算術運算控制迴圈的次數:#! /bin/shCOUNTER=1while [ "$COUNTER" -lt 10 ]; do echo "Here we go again" COUNTER=$(($COUNTER+1))done
(3)case 和 while 結合
#!/bin/bashwhile : :表示真,一直迴圈do 要迴圈執行的命令 echo -n "enter any number [1-5]:" 輸入序號1-5 read nu 設定read的變數 case $nu in 進行選擇,輸入的要是1-5的數字 1|2|3|4|5) echo "enter anumber 1 and 5" 就迴圈這一行,讓你不停的輸入1-5 ;; *) 如果輸入的不是1-5的數字 echo -n "wrong number, continue (y/n?:)" 詢問你是否繼續 read con 設定read的變數 case $con in 進行選擇,看是不是y|yes|Y|YES這幾個 y|yes|Y|YES) continue 如果是,那麼就跳過,讓你重新輸入,如果不是 ;; *) 那麼就執行這個break退出迴圈 break ;; esac esacdone
Shell 指令碼實踐