1

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?

2
  • given you've got 8 options in there, you'd have to write out 8! = 40,320 if cases to handle all possible inputs. Good luck with that. You'd be better off learning how to disect 146 into individual digits and checking for those only. that'll reduce your code to a split operation + loop, and 8 if tests. Commented Jan 7, 2015 at 15:01
  • Well I put that code in there so I just don't demand solution out of nothing, And I was also hoping that my code can be modified to achieve some simpler solution that will also work with variation answers like 145 giving the same result as 451. So dissection of numbers is desired, but don't know how to approach it. Commented Jan 7, 2015 at 15:07

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That is exactly solution I was hoping for! Works perfect, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.