Home » Bash Until Loop

Bash Until Loop

In this topic, we have defined how to use until loop statement in Bash Script.

The while loop is a great option to execute a set of commands when some condition evaluates to true. Sometimes, we need to execute a set of commands until a condition evaluates to true. In such cases, Bash until loop is useful.

Bash Until Loop in a bash scripting is used to execute a set of commands repeatedly based on the boolean result of an expression. The set of commands are executed only until the expression evaluates to true. It means that when the expression evaluates to false, a set of commands are executed iteratively. The loop is terminated as soon as the expression evaluates to true for the first time.

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

Syntax

The syntax of until loop looks almost similar to the syntax of bash while loop. But there is a big difference in the functionalities of both. The syntax of bash until loop can be defined as:

If there are multiple conditions in the expression, then the syntax will be as follows:

Some of the key points of until loop are given below:

  • The condition is checked before executing the commands.
  • The commands are only executed if the condition evaluates to false.
  • The loop is terminated as soon as 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 at least once.

Examples of Bash Until Loop

Following are some examples of bash until loop illustrating different scenarios to help you understand the usage and working of it:

Until Loop with Single Condition

In this example, the until loop contains a single condition in expression. It is the basic example of until loop which will print series of numbers from 1 to 10:

Example

Output

Bash Until Loop

Until Loop with Multiple Conditions

Following is an example with multiple conditions in an expression:

Example

Output

Bash Until Loop

Conclusion

In this topic, we have learned about the syntax of until loop statement in bash scripting for single and multiple conditions in expression with example scripts.


Next TopicBash String

You may also like