Shell Scripting 101: Until Loop in Shell Scripts

Continuing our series, in today’s article, we’ll go over the until loop in shell scripts. We’ve already covered for loops and while loops in shell scripts in our previous tutorials. You’ll find a lot of similarities in the while and until loop so we’ll also look at the differences between both the loops in this article.

While Loop vs Until Loop in Shell Scripts

Both the loops work in a very similar fashion where they accept one condition based on which the loop continues. The main difference between the two loops is how they behave based on the conditions passed to them:

  • While Loop – Runs until the condition is TRUE. Stops when the condition returns FALSE.
  • Until Loop – Runs until the condition is FALSE. Stops when the condition returns TRUE.

This simple explanation of both the loops should give you an idea of why there are two different loops instead of just having one.

Creating until Loop in Shell Scripts

Now you know exactly what the until loop is, let’s get into the technical aspects of it and make an until loop. The syntax is the same as that of a while loop, so go ahead and read that tutorial if you haven’t already.

Basic syntax of the until loop:

until [ condition ]
do
    ... commands to run ...
done

Here’s an example of a basic until loop:

num=1
until [ $num -gt 6 ]
do
   echo "The variable is $num"
   ((num++))
done

In the above example, we initialized the variable num with the value 1. The until loop continues to run as long as the variable num is not greater than 6. So the loop will run 6 times since the condition doesn’t become true until variable num becomes 7.

The ((i++)) part is discussed in one of our previous loop topics. But in simple words, the double parenthesis (( )) allow us to run C style operations within bash scripts.

Until Loop in shell scripts
Until Loop

Do You Really Need the until Loop?

Well, yes and no. The until loop is similar to having a while loop with a negated condition (with an exclamation mark to negate the condition). So it doesn’t really make much of a difference. But for semantics, having two different loops makes things easier for a person reading the code.

Conclusion

We hope you have understood the usage and the reason behind the use of the until loop in shell scripts. Do continue to follow through as we keep posting on the topics of shell scripting 101.