Bash
Linux - 案例命令
如何在菜單列表中有空格或製表符?
PS3='Please enter your choice: ' options=("Option 1" "Option 2" "Quit") select opt in "${options[@]}" do case $opt in "Option 1") echo "Your choise is 1" ;; "Option 2") echo "Your choise is 2" ;; "Quit") break ;; *) echo "Invalid option;; esac done
我得到了這個:
[user@Server:/home/user] ./test.sh 1) Option 1 2) Option 2 3) Option 3 4) Quit Please enter your choice:
但我想要這樣的東西:
[user@Server:/home/user] ./test.sh 1) Option 1 2) Option 2 3) Option 3 4) Quit Please enter your choice:
想法?
中的
select
語句bash
,即顯示菜單的內容,不允許為菜單指定縮進。
case
只是對程式碼的評論:讓語句作用通常$REPLY
比使用所選字元串的變數更容易。它使您不必輸入兩次字元串。例如
select opt in "${options[@]}" do case $REPLY in 1) echo "Your choice is 1" ;; 2) echo "Your choice is 2" ;; 3) break ;; *) echo 'Invalid option' >&2 esac done
或者,對於這個特定的例子,
select opt in "${options[@]}" do case $REPLY in [1-2]) printf 'Your choice is %s\n' "$REPLY" ;; 3) break ;; *) echo 'Invalid option' >&2 esac done
(大致)
select
手動重新實現和微調顯示並不難,至少只要您沒有太多選項需要多列列表。#!/bin/bash # print the prompt from $1, and a menu of the other arguments choose() { local prompt=$1 shift local i=0 for opt in "$@"; do # we have to do the numbering manually... printf " %2d) %s\n" "$((i += 1))" "$opt" done read -p "$prompt: " } options=("Foo" "Bar" "Quit") while choose 'Please enter your choice' "${options[@]}"; do case $REPLY in 1) echo "you chose 'foo'" ;; 2) echo "you chose 'bar'";; 3) echo 'you chose to quit'; break;; *) echo 'invalid choice';; esac done
當然,這可以擴展為將數組鍵(索引)考慮在內,並將它們顯示為菜單中的選項,而不是執行計數器。