Until Loop

Bash Scripting Until Loop Examples

until loop


The Bash until loop executes its commands between the "do" and "done" statements as long as the condition evaluates to true. The loop is exited if the condition is false:

Basic Syntax of an until loop:




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

Basic example of an until loop:



#!/bin/bash
#
count=1
until [ $count -gt 5 ]
do
  printf "Count has a value of $count\n"
  ((count++))
done

In the above "until" loop example, we initially set the count variable to a value of "1". The next line "until [ $count -gt 5 ]" basically is the instruction to continue repeating the code between the "do" and "done" statements until our $count variable has a value greater than "5". The variable count is incremented each time the code between the "do" and "done" statements are executed.

Output from the above until loop script:



john@john-desktop:~/scripts$ ./until1.sh 
Count has a value of 1
Count has a value of 2
Count has a value of 3
Count has a value of 4
Count has a value of 5