Bash

Bash Until loop

Bash Until loop

Bash Until Loop

In this topic, we've defined the way to use until loop statement in Bash Script.

The while loop may be a great choice to execute a group of commands when some condition evaluates to true. Sometimes, we'd like to execute a group of commands until a condition evaluates to true. In such cases, Bash until loop is beneficial.

Bash Until Loop during a bash scripting is employed to execute a group of commands repeatedly supported the Boolean results of an expression. The collection of instructions is executed only until the expression is true. It means when the expression evaluates to false, a group of commands are executed iteratively. The loop is terminated as soon because the expression evaluates to true for the primary time.

In short, the until loop is analogous to the while loop but with a reverse concept.

Syntax

The syntax of until loop looks almost almost like the syntax of bash while loop. But there's an enormous difference within the functionalities of both. The syntax of bash until loop are often defined as:

until [ expression ]; 
do 
command1 
command2 
. . . 
. . . . 
commandN 
done 
If there are multiple conditions within the expression, then the syntax are going to be as follows:

until [[ expression ]]; 
do 
command1 
command2 
. . . 
. . . . 
commandN 
done 

Few key facts about Bash until loop to keep in mind:

The condition is reviewed before executing the commands.

The instruction is only executed if the condition turns to be false.

The loop is stopped as soon because the condition evaluates to true.

The program control is transferred to the command that follows the 'done' keyword after the termination.

The while loop vs. the until loop

The 'until loop' commands execute until a non-zero status is returned.

The 'while loop' commands execute until a zero status is returned.

The until loop contains property to be executed a minimum of once.

Examples of Bash Until Loop

Following are some samples of bash until loop illustrating different scenarios to assist you to understand the usage and dealing of it:

Until Loop with Single Condition

In this example, the until loop contains one condition in expression. it's the essential example of until loop which can print series of numbers from 1 to 10:

#!/bin/bash  
#Bash Until Loop example with a single condition  
  
i=1  
until [ $i -gt 10 ]  
do  
echo $i  
((i++))  
done  

The Output of the above code snippet:
Text

Description automatically generated with medium confidence

Example 2:

In this example we have used more than one conditions to see how it works with them.

#!/bin/bash  
#Bash Until Loop example with numerous conditions  
  
max=5  
a=1  
b=0  
  
until [[ $a -gt $max || $b -gt $max ]];  
do  
echo "a = $a & b = $b."  
((a++))  
((b++))  
done