Bash:多项选择合二为一 variable/array

Bash: Multiple choices put into one variable/array

我正在尝试找出这个场景的代码:

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

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

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

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"