Shell 指令碼實踐

來源:互聯網
上載者:User

標籤:

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 指令碼實踐

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.