cat if1.sh #!/bin/sh a=10 b=20 if [ $a -eq $b ]; then echo "a is equal to b"; fi if [ $a -gt $b ]; then echo "a is great than b"; fi if [ $a -lt $b ] then echo "a is less than b"; fi # the EOF
寫法上有兩種常見風格,一種把 then 接在條件後面用分號隔開,另一種讓 then 換行獨立,端看個人習慣。
若要改由命令列傳入參數,把變數換成位置參數即可:
#!/bin/sh # a=10 # b=20 if [ $1 -eq $2 ]; then echo "the first number is equal to the second"; fi if [ $1 -gt $2 ]; then echo "the first number is great than the second"; fi if [ $1 -lt $2 ] then echo "the first number is less than the second"; fi # the EOF
執行時以空格分隔參數:
sh if1.sh 1 2 the first number is less than the second sh if1.sh 12 1 the first number is great than the second
if [ expression ] then statement(s) to be executed if expression is true else statement(s) to be executed if expression is not true fi
一個實用的參數檢查範例:
cat ifparam.sh #!/bin/sh if [ $# -lt 3 ]; then echo "Usage:`basename $0` arg1 arg2 arg3" >&2 exit 1 fi #EOF echo "arg1:$1" echo "arg1:$2" echo "arg1:$3"
重點:$# 是參數個數;basename $0 印出腳本名稱;>&2 把訊息送到 stderr 當作錯誤輸出。
sh ifparam.sh scott tom Usage:ifparam.sh arg1 arg2 arg3
再看一個環境變數判斷的例子:
#!/bin/csh
#if [ -z $EDITOR ] ① 直接報錯:語法錯誤
#if [ `echo $EDITOR | wc -c` -eq 0 ] ② wc -c 會把空行算進去,不準確
if [ -z "`echo $EDITOR`" ] ③ 正確寫法
then
echo "Your EDITOR environment is not set"
else
echo "Using $EDITOR as the default editor"
endif
#EOF
test 的 -z 表示「字串長度為 0 時回傳 true」,因此加上引號後才是可靠的空值判斷。
if [ expression 1 ]; then statement(s) ... elif [ expression 2 ]; then statement(s) ... else statement(s) ... fi
比較兩數大小的範例,注意 == 在 test 中並非標準運算子:
sh elif.sh 10 20 elif.sh: test: unknown operator ==
把 == 改為 -eq 就能正常運作。若想保留錯誤訊息,可重導向到檔案:
sh elif.sh 10 20 > log.txt 2>&1
#!/bin/sh
DIR=$1
if [ "$DIR" = "" ]; then
echo "Usage:`basename $0` directory to create" >&2
exit 1
fi
if [ -d $DIR ]; then
echo "Directory $DIR exists"
else
echo "The Directory does exist"
echo -n "Create it now?[y..n]:"
read ANS
if [ "$ANS" = "y" ] || [ "$ANS" = "Y" ]; then
echo "creating now"
mkdir $DIR > log.txt 2>&1
if [ $? -ne 0 ]; then
echo "Errors creating the directory $DIR" >&2
exit 1
fi
echo "Creating successful"
elif [ "$ANS" = "n" ] || [ "$ANS" = "N" ]; then
echo "Giving up creating directory $DIR"
else
echo "Bad input"
fi
fi
#EOF
四種執行情境:
sh ifmkdir.sh Usage:ifmkdir.sh directory to create sh ifmkdir.sh test Directory test exists sh ifmkdir.sh test1 Create it now?[y..n]:y → Creating successful sh ifmkdir.sh test2 Create it now?[y..n]:d → Bad input