Creating an interactive while loop

In reality, you will not use a while loop that often. In most scenarios, a for loop is better (as we will see later on in this chapter). There is, however, one situation where a while loop is excellent: dealing with user input. If you use the while true construct with an if-then-else block nesting within it, you can keep asking the user for input until you get the answer you're looking for. The following example, which is a simple riddle, should clarify matters:

reader@ubuntu:~/scripts/chapter_11$ vim while-interactive.sh 
reader@ubuntu:~/scripts/chapter_11$ cat while-interactive.sh
#!/bin/bash

#####################################
# Author: Sebastiaan Tammer
# Version: v1.0.0
# Date: 2018-10-27
# Description: A simple riddle in a while loop.
# Usage: ./while-interactive.sh
#####################################

# Infinite loop, only exits on correct answer.
while true; do
read -p "I have keys but no locks. I have a space but no room. You can enter, but can’t go outside. What am I? " answer
if [[ ${answer} =~ [Kk]eyboard ]]; then # Use regular expression so 'a keyboard' or 'Keyboard' is also a valid answer.
echo "Correct, congratulations!"
exit 0 # Exit the script.
else
# Print an error message and go back into the loop.
echo "Incorrect, please try again."
fi
done

reader@ubuntu:~/scripts/chapter_11$ bash while-interactive.sh
I have keys but no locks. I have a space but no room. You can enter, but can’t go outside. What am I? mouse
Incorrect, please try again.
I have keys but no locks. I have a space but no room. You can enter, but can’t go outside. What am I? screen
Incorrect, please try again.
I have keys but no locks. I have a space but no room. You can enter, but can’t go outside. What am I? keyboard
Correct, congratulations!
reader@ubuntu:~/scripts/chapter_11$

In this script, we use read -p to ask the user a question, and we store the reply in the answer variable. We then use a nested if-then-else block to check if the user gave the correct answer. We use a simple regular expression if-condition, ${answer} =~ [Kk]eyboard, which gives a little flexibility to the user with regards to capitals and perhaps the word a in front. For every incorrect answer, the else statement prints an error and the loop starts back at read -p. If the answer is correct, the then block is executed, which ends with exit 0 to signify the end of the script. As long as the correct answer isn't given, the loop will go on forever.

You might see a problem with this script. If we wanted to do anything after the while loop, we'd need to break out of it without exiting the script. We will see how we can achieve this with the – wait for it – break keyword! But first, we'll check out the for loop.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.53.119