1

How do you exit a while loop in bash when user input detects "done"?

The objective is to have users input restaurant names and when they type done, the while loop escapes and and it randomly spits out a random restaurant within the array? As of right now, it only escapes when CTRL + D but this also closes the terminal

P.S: I've only been playing with bash for about 2 hours!

echo 'Where are you having trouble deciding? Type done to finish'

while read restaurants
do
  rest_array=("${rest_array[@]}" $restaurants)
done


echo Eat at ${rest_array[$rand]}
2
  • Use the break command to exit any loop. Commented Feb 14, 2020 at 16:25
  • 1
    rest_array+=("$restaurants") is a simpler way to append to the array. Commented Feb 14, 2020 at 16:31

1 Answer 1

1

Use break to exit the loop in bash

echo 'Where are you having trouble deciding? Type done to finish'

while read restaurants
do
  if [[ "$restaurants" == "done" ]]; then
     break
  fi
  rest_array+=("$restaurants")
done


echo Eat at ${rest_array[$rand]}
Sign up to request clarification or add additional context in comments.

9 Comments

I tried this way but it closes out of the script completely (using WIN10)
What kind of shell are you using?
Using bash, file name randomrest.sh
It's strange. Can you explain "it closes out of the script completely" please?
Sure. When I open the script (double clicking the script file), I input relevant texts, and once I type done then enter, the bash window just closes as if I type CTRL + D or X out the window. I hope I'm describing it properly
|

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.