Reputation: 81
I am trying to figure out the code for this scenario:
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
My limited knowledge can do one at time:
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
I suppose perhaps I could be adding each number entered into array? Then perhaps case esac loop won't be the best solution?
Upvotes: 1
Views: 176
Reputation: 361605
You could store the fruits in an array, and use the ==
operator with [[
to check for wildcard matches.
mix=()
[[ $selection == *[17]* ]] && mix+=(Apples)
[[ $selection == *[27]* ]] && mix+=(Pears)
[[ $selection == *[37]* ]] && mix+=(Plums)
...
echo "Your cocktail will contain: ${mix[@]:-no fruits}"
If $selection
contains 1
or 7
, add "Apples"
to the array. If it contains 2
or 7
, add "Pears"
. And so on.
The :-
part substitutes the string "no fruits"
if the array is empty.
Upvotes: 3