case和select結構在技術上說並不是循環, 因為它們並不對可執行代碼塊進行迭代. 但是和循環相似的是, 它們也依靠在代碼塊頂部或底部的條件判斷來決定程序的分支.
select
select結構是建立菜單的另一種工具, 這種結構是從ksh中引入的.
select variable [in list]
do
TT class="REPLACEABLE" >command...
break
done
提示用戶輸入選擇的內容(比如放在變量列表中). 注意: select命令使用PS3提示符, 默認為(#?), 當然, 這可以修改.
#!/bin/bash PS3='Choose your favorite vegetable: ' # 設置提示符字串. echo select vegetable in "beans" "carrots" "potatoes" "onions" "rutabagas" do echo echo "Your favorite veggie is $vegetable." echo "Yuck!" echo break # 如果這里沒有 'break' 將不停循環進行選擇 done exit 0
如果忽略了in list列表, 那么select命令將會使用傳遞到腳本的命令行參數($@), 或者是函數參數(當select是在函數中時).
與忽略in list的
for variable [in list]
結構比較一下.
例: 使用函數中的select結構來創建菜單
#!/bin/bash PS3='Choose your favorite vegetable: ' echo choice_of() { select vegetable # [in list]被忽略, 所以'select'使用傳遞給函數的參數. do echo echo "Your favorite veggie is $vegetable." echo "Yuck!" echo break done } choice_of beans rice carrots radishes tomatoes spinach # $1 $2 $3 $4 $5 $6 # 傳遞給choice_of()的參數 exit 0
case (in) / esac
在shell中的case結構與C/C++中的switch結構是相同的. 它允許通過判斷來選擇代碼塊中多條路徑中的一條. 它的作用和多個if/then/else語句的作用相同, 是它們的簡化結構, 特別適用於創建菜單.
case "$variable" in
"$condition1" )
TT class="REPLACEABLE" >command...
;;
"$condition2" )
TT class="REPLACEABLE" >command...
;;
esac
例: 簡單的字符串匹配
#!/bin/bash # match-string.sh: 簡單的字符串匹配 match_string () { MATCH=0 NOMATCH=90 PARAMS=2 # 此函數需要2個參數. BAD_PARAMS=91 [ $# -eq $PARAMS ] || return $BAD_PARAMS case "$1" in "$2") return $MATCH;; * ) return $NOMATCH;; esac } a=one b=two c=three d=two match_string $a # 參數個數錯誤. echo $? # 91 match_string $a $b # 不匹配 echo $? # 90 match_string $b $d # 匹配 echo $? # 0 exit 0
