1. 程式人生 > >Shell指令碼語法-- if/then/elif/else/fi

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

和C語言類似,在Shell中用ifthenelifelsefi這幾條命令實現分支控制。這種流程控制語句本質上也是由若干條Shell命令組成的,例如先前講過的

if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

其實是三條命令,if [ -f ~/.bashrc ]是第一條,then . ~/.bashrc是第二條,fi是第三條。如果兩條命令寫在同一行則需要用;號隔開,一行只寫一條命令就不需要寫;號了,另外,then後面有換行,但這條命令沒寫完,Shell會自動續行,把下一行接在then後面當作一條命令處理。和[命令一樣,要注意命令和各引數之間必須用空格隔開。if

命令的引數組成一條子命令,如果該子命令的Exit Status為0(表示真),則執行then後面的子命令,如果Exit Status非0(表示假),則執行elifelse或者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"
fi
if :; 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_NO
if [ "$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 1
fi
exit 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