Breaking the loop

For some scripting logic, it will prove necessary to break out of the loop. You might imagine that, in one of your scripts, you are waiting for something to finish. As soon as that happens, you want to do something. Waiting and periodically checking inside a while true loop could be an option for this, but if you recall in the while-interactive.sh script, we exited on the successful answer to the riddle. On an exit, we cannot run any more commands that are outside of the while loop! This is where break comes into play. It allows us to exit the loop, but continue the script. First, let's update while-interactive.sh to make use of this loop control keyword:

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.1.0
# Date: 2018-10-28
# 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!"
break # Exit the while loop.
else
# Print an error message and go back into the loop.
echo "Incorrect, please try again."
fi
done

# This will run after the break in the while loop.
echo "Now we can continue after the while loop is done, awesome!"

We made three changes:

  • Adopted a higher version number
  • Replaced exit 0 with break
  • Added a simple echo after the while loop

When we still had exit 0 in place, the final echo would never have run (but don't trust us, be sure to verify this yourself!). Now, run it with break and watch:

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? keyboard
Correct, congratulations!
Now we can continue after the while loop is done, awesome!

There we go, code execution after a broken while loop. Often, after an infinite loop, there is definitely other code that needs to be executed, and this is the way to do it.

We can use break not only in a while loop, but most certainly in a for loop. The following example shows how we can use break in a for loop:

reader@ubuntu:~/scripts/chapter_11$ vim for-loop-control.sh
reader@ubuntu:~/scripts/chapter_11$ cat for-loop-control.sh
#!/bin/bash

#####################################
# Author: Sebastiaan Tammer
# Version: v1.0.0
# Date: 2018-10-28
# Description: Loop control in a for loop.
# Usage: ./for-loop-control.sh
#####################################

# Generate a random number from 1-10.
random_number=$(( ( RANDOM % 10 ) + 1 ))

# Iterate over all possible random numbers.
for number in {1..10}; do

if [[ ${number} -eq ${random_number} ]]; then
echo "Random number found: ${number}."
break # As soon as we have found the number, stop.
fi

# If we get here the number did not match.
echo "Number does not match: ${number}."
done
echo "Number has been found, all done."

At the top of this script's functionality, a random number between 1 and 10 is determined (don't worry about the syntax). Next, we iterate over the numbers 1 through 10 and for each number, we'll check if it's equal to the randomly generated number. If it is, we print a success message and we break the loop. Otherwise, we're going outside of the if-then block and printing the failure message. If we did not include the break statement, the output would look like this:

reader@ubuntu:~/scripts/chapter_11$ bash for-loop-control.sh 
Number does not match: 1.
Number does not match: 2.
Number does not match: 3.
Random number found: 4.
Number does not match: 4.
Number does not match: 5.
Number does not match: 6.
Number does not match: 7.
Number does not match: 8.
Number does not match: 9.
Number does not match: 10.
Number has been found, all done.

Not only do we see the number printed as both matching and non-matching (which is a logical error, of course), but the script also continues checking all other numbers when we're certain that those will not match. Now, if we used exit instead of break, the final statement will never be printed:

reader@ubuntu:~/scripts/chapter_11$ bash for-loop-control.sh 
Number does not match: 1.
Number does not match: 2.
Number does not match: 3.
Number does not match: 4.
Number does not match: 5.
Number does not match: 6.
Random number found: 7.

Only by using break will we get exactly the amount of output we need; nothing more and nothing less. You might have seen that we could have also used an else clause for the Number does not match: message. Still, nothing would be stopping the program. So even if the random number was found on the first try (which will happen, eventually), it will still compare all of the values in the list until it reaches the end of that list.

Not only is this a waste of time and resources, but imagine the output if the random number was somewhere between 1 and 1,000,000! Just remember: if you're done with the loop, break out of it.

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

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