Site icon DesignLinux

Bash until Loop

Bash until Loop

Loops are primary requirement of any programming languages. Loops are useful when you want to execute a series of commands until the certain condition is satisfied. In Bash, loops are useful for automating repetitive tasks. There are three basic loops for loop, while loop , and until loop. In this tutorial, we will see basics of until loop in Bash.

Bash until Loop

The until loop is used to perform the given set of commands for n number of times until the given condition is not false.

Below is the primary form of until loop in Bash:

until [CONDITION]
do
  [COMMANDS]
done

The until statement starts with the until keyword and followed by the conditional expression.

It will first check the condition before executing the commands. If the condition is false then commands will be executed. Otherwise, the loop terminates and program control goes to next command.

For example, to print the number which increment by one, until the condition evaluates to false.

#!/bin/bash

counter=0

until [ $counter -gt 5 ]
do
  echo Counter: $counter
  ((counter++))
done

The loop iterates as long as the counter variable has a value greater than four. It will show the following output:

Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5

You can break the loop execution using break and continue statements.

Bash until Loop Example

If you are using git and your git host has downtime then, you should type git pull multiple times manually until the host is online. Instead of that you can run the following script once. It will check until it successful and try to pull the repository.

#!/bin/bash

until git pull &> /dev/null
do
    echo "Still waiting for the git host ..."
    sleep 1
done

echo -e "\nThe git repository is pulled"

The script will print “Still waiting for the git host …” and sleep for one second until the git host goes online. Once the repository is pulled, it will print “The git repository is pulled“.

Still waiting for the git host ...
Still waiting for the git host ...
Still waiting for the git host ...

The git repository is pulled.

Conclusion

In this article you learned how to use the until loops in bash script. The while and until loops are similar to each other.

If you have any questions or feedback, please feel free to leave a comment.

Exit mobile version