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

Bash:将多个选项放入一个变量/数组中,bash,variables,multiple-choice,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 Pl

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

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
包含
1
7
,则向数组中添加
“Apples”
。如果它包含
2
7
,则添加
“Pears”
。依此类推


:-
部分替换字符串
“无果实”
如果数组是空的。

如果你有8个选项,你必须写出8!=40320
if
案例来处理所有可能的输入。祝你好运。你最好学会如何将
146
分离成单个数字,并只检查这些数字。这将把你的代码简化为拆分操作+循环,一个d 8
if
测试。我把代码放在那里,这样我就不会要求从无到有的解决方案,我也希望我的代码可以被修改,以获得一些更简单的解决方案,也能与变量答案一起工作,比如145,给出与451相同的结果。所以需要对数字进行剖析,但不知道如何处理。也就是说这正是我希望的解决方案!非常好,谢谢!