Shell select 迴圈


select 迴圈提供了一個簡單的方法來建立一個編號的選單,使用者可從中選擇。它是有用的,當你需要從列表中選擇,要求使用者選擇一個或多個專案。

語法

select var in word1 word2 ... wordN
do
   Statement(s) to be executed for every word.
done

var是一個變數,word1 到 wordN是由空格分隔的字元(字)序列的名稱。每次for迴圈的執行,變數var的值被設定為下一個單詞的列表中的字,由 word1 到wordN。

對於每一個選擇的一組命令將被執行,在迴圈中。這個迴圈在ksh,並已被改編成的bash。這不是在sh。

例子:

下面是一個簡單的例子,讓使用者選擇的首選飲品:

#!/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 迴圈的選單看起來像下面這樣:

$./test.sh
1) tea
2) cofee
3) water
4) juice
5) appe
6) all
7) none
#? juice
Available at home
#? none
$

您可以更改顯示的提示選擇迴圈通過改變變數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
$