Bash Until Loop
Bash Until Loop is a loop statement used to execute a block of statements repeatedly based on the boolean result of an expression. The block of statements are executed until the expression returns true.
This might be little tricky. Let us understand this in much more detailed manner. When the expression evaluates to FALSE, the block of statements are executed iteratively. For the first time when the expression evaluates to TRUE, the loop is broken.
Syntax of Bash Until Loop
The syntax of until loop might look similar to that of bash while loop. But there is a difference in functionality
until [ expression ]; do statement(s) done
The expression can contain only one condition. If the expression should have multiple conditions, the syntax is as follows :
until [[ expression ]]; do statement(s) done
Example of bash until loop
Following is an until loop with only one condition in expression.
Bash Script File
#!/bin/bash count=10 i=20 # until loop with single condition until [ $i -lt $count ]; do echo "$i" let i-- done
When the above until loop script is run in terminal, we will get the following output.
Output
$ ./bash-until-loop-example 20 19 18 17 16 15 14 13 12 11 10
Example of bash until loop
Following is an until loop with only multiple conditions in expression.
Bash Script File
#!/bin/bash count=10 a=20 b=16 # until loop for multiple conditions in expression until [[ $a -lt $count || $b -lt count ]]; do echo "a : $a, b : $b" let a-- let b-- done
When the above until loop script is run in terminal, we will get the following output.
Output
$ ./bash-until-loop-example-2 a : 20, b : 16 a : 19, b : 15 a : 18, b : 14 a : 17, b : 13 a : 16, b : 12 a : 15, b : 11 a : 14, b : 10
To realize looping in bash, we have bash for loop and bash while loop along with until loop statement.
Conclusion
In this Bash Tutorial – Bash Until Loop Statements, we have learnt about syntax of until loop statement in bash scripting for single and multiple conditions in expression with example scripts.