Bash:将多个选项放入一个变量/数组中

时间:2015-01-07 14:57:53

标签: bash variables multiple-choice

我正在试图弄清楚这种情况的代码:

Mix your favourite fruit:
1 Apples
2 Pears
3 Plums
4 Peach
5 Pineapple
6 Strawberry
7 All
8 None

Selection:146

Your cocktail will contain: Apples Peach Strawberry

我的有限知识可以做到一次:

echo "Mix your favourite fruit:
1 Apples
2 Pears
3 Plums
4 Peach
5 Pineapple
6 Strawberry
7 All
8 None"

echo Selection:
read selection

case $selection in
1)
mix=Apples
;;
2)
mix=Pears
;;
..
..
12)
mix="Aples Pears"
;;
7)
mix=123456(this is wrong)
;;
8)
mix=no fruits
;;
esac

echo Your cocktail will contain: $mix

我想也许我可以添加输入到数组中的每个数字?那么也许案例esac循环不是最好的解决方案?

1 个答案:

答案 0 :(得分:3)

您可以将水果存储在数组中,并使用==运算符和[[来检查通配符匹配。

mix=()

[[ $selection == *[17]* ]] && mix+=(Apples)
[[ $selection == *[27]* ]] && mix+=(Pears)
[[ $selection == *[37]* ]] && mix+=(Plums)
...

echo "Your cocktail will contain: ${mix[@]:-no fruits}"

如果$selection包含17,请将"Apples"添加到数组中。如果它包含27,请添加"Pears"。等等。

如果数组为空,:-部分将替换字符串"no fruits"