The until loop

While has a twin: until. An until loop does exactly what while does, with only one difference: the loop only runs as long as the condition is false. As soon as the condition becomes true, the loop no longer runs. We'll make some minor changes to the previous script and we'll see how until works:

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

#####################################
# Author: Sebastiaan Tammer
# Version: v1.0.0
# Date: 2018-10-27
# Description: Example of an until loop with a counter.
# Usage: ./until-counter.sh
#####################################

# Define the counter outside of the loop so we don't reset it for
# every run in the loop.
counter=0

# This loop runs 10 times.
until [[ ${counter} -gt 9 ]]; do
counter=$((counter+1)) # Increment the counter by 1.
echo "Hello! This is loop number ${counter}."
sleep 1
done

# After the while-loop finishes, print a goodbye message.
echo "All done, thanks for tuning in!"

As you can see, the changes to this script are very minimal (but important, nonetheless). We replaced while with until, -lt with -gt, and 10 with 9. Now, it reads run the loop until the counter is greater than 9 as opposed to run the loop as long as the counter is lower than 10. Because we are using lower than and greater than, we have to change the number, otherwise we're going to experience the famous off-by-one error (which, in this case, means that we'll loop 11 times, should we not have changed the 10 to a 9; try it!).

In essence, the while and until loops are exactly the same. You will use a while loop more often than an until loop: since you can just negate the condition, a while loop will always work. However, sometimes, an until loop might feel more justified. In any case, use the one that is easiest to comprehend for the situation! When in doubt, just using while will hardly ever be wrong, as long as you get the condition right.

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

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