Unix/Linux Shell - select迴圈



select迴圈提供了一種簡單的方法來建立一個編號選單,使用者可以從中選擇選項。當您需要讓使用者從一系列選項中選擇一個或多個專案時,它非常有用。

語法

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

這裡var是變數名,word1wordN是由空格分隔的字元序列(單詞)。每次for迴圈執行時,變數var的值都設定為單詞列表word1wordN中的下一個單詞。

對於每次選擇,都會在迴圈內執行一組命令。此迴圈是在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來更改select迴圈顯示的提示:

$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
$
unix-shell-loops.htm
廣告