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
$