1

我正在尝试找出这种情况的代码:

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循环不是最好的解决方案?

4

1 回答 1

3

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

mix=()

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

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

如果$selection包含1or 7,则添加"Apples"到数组中。如果它包含27,则添加"Pears"。等等。

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

于 2015-01-07T15:07:48.170 回答