Shell指令碼文法--if/then/elif/else/fi

來源:互聯網
上載者:User


Shell指令碼文法--if/then/elif/else/fi 和C語言類似,在Shell中用if、then、elif、else、fi這幾條命令實現分支控制。這種流程式控制制語句本質上也是由若干條Shell命令組成的,例如先前講過的  www.2cto.com  if [ -f ~/.bashrc ]; then    . ~/.bashrcfi其實是三條命令,if [ -f ~/.bashrc ]是第一條,then . ~/.bashrc是第二條,fi是第三條。如果兩條命令寫在同一行則需要用;號隔開,一行唯寫一條命令就不需要寫;號了,另外,then後面有換行,但這條命令沒寫完,Shell會自動續行,把下一行接在then後面當作一條命令處理。和[命令一樣,要注意命令和各參數之間必須用空格隔開。if命令的參數組成一條子命令,如果該子命令的Exit Status為0(表示真),則執行then後面的子命令,如果Exit Status非0(表示假),則執行elif、else或者fi後面的子命令。if後面的子命令通常是測試命令,但也可以是其它命令。Shell指令碼沒有{}括弧,所以用fi表示if語句塊的結束。見下例:#! /bin/sh if [ -f /bin/bash ]then echo "/bin/bash is a file"else echo "/bin/bash is NOT a file"fiif :; then echo "always true"; fi:是一個特殊的命令,稱為空白命令,該命令不做任何事,但Exit Status總是真。此外,也可以執行/bin/true或/bin/false得到真或假的Exit Status。再看一個例子:#! /bin/sh echo "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上例中的read命令的作用是等待使用者輸入一行字串,將該字串存到一個Shell變數中。此外,Shell還提供了&&和||文法,和C語言類似,具有Short-circuit特性,很多Shell指令碼喜歡寫成這樣:test "$(whoami)" != 'root' && (echo you are using a non-privileged account; exit 1)&&相當於“if...then...”,而||相當於“if not...then...”。&&和||用於串連兩個命令,而上面講的-a和-o僅用於在測試運算式中串連兩個測試條件,要注意它們的區別,例如,test "$VAR" -gt 1 -a "$VAR" -lt 3和以下寫法是等價的test "$VAR" -gt 1 && test "$VAR" -lt 3 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.