select 循環(huán)提供了一個(gè)簡(jiǎn)單的方法來創(chuàng)建一個(gè)編號(hào)的菜單,用戶可從中選擇。它是有用的,當(dāng)你需要從列表中選擇,要求用戶選擇一個(gè)或多個(gè)項(xiàng)目。
select var in word1 word2 ... wordN do Statement(s) to be executed for every word. done
var是一個(gè)變量,word1 到 wordN是由空格分隔的字符(字)序列的名稱。每次for循環(huán)的執(zhí)行,變量var的值被設(shè)置為下一個(gè)單詞的列表中的字,由 word1 到wordN。
對(duì)于每一個(gè)選擇的一組命令將被執(zhí)行,在循環(huán)中。這個(gè)循環(huán)在ksh,并已被改編成的bash。這不是在sh。
下面是一個(gè)簡(jiǎn)單的例子,讓用戶選擇的首選飲品:
#!/bin/ksh select DRINK in tea cofee water juice appe all none do case $DRINK in tea|cofee|water|all) echo "Go to canteen" ;; juice|appe) echo "Available at home" ;; none) break ;; *) echo "ERROR: Invalid selection" ;; esac done
select 循環(huán)的菜單看起來像下面這樣:
$./test.sh 1) tea 2) cofee 3) water 4) juice 5) appe 6) all 7) none #? juice Available at home #? none $
您可以更改顯示的提示選擇循環(huán)通過改變變量PS3如下:
$PS3="Please make a selection => " ; export PS3 $./test.sh 1) tea 2) cofee 3) water 4) juice 5) appe 6) all 7) none Please make a selection => juice Available at home Please make a selection => none $