LinuxCommandLibrary

until

Execute commands repeatedly until condition is true

TLDR

Execute a command until it succeeds

$ until [command]; do :; done
copy

Wait for a systemd service to be active
$ until systemctl is-active [[-q|--quiet]] [nginx]; do [echo "Waiting..."]; sleep 1; done; [echo "Launched!"]
copy

SYNOPSIS

until condition; do commands; done

PARAMETERS

condition
    A sequence of commands whose exit status determines whether the loop continues. Usually a test condition.

commands
    The sequence of commands to be executed repeatedly.

DESCRIPTION

The until command in Linux repeatedly executes a sequence of commands until a specified condition becomes true. It's a fundamental control flow structure in shell scripting, enabling you to create loops that continue until a certain exit status is achieved. The condition is evaluated after each iteration. The command list is run as long as the exit status of the last command in the condition is not zero.

Until loops are commonly used for tasks such as waiting for a file to be created, retrying an operation until it succeeds, or processing data until a certain marker is reached. It provides a clean and concise way to express these types of iterative processes within shell scripts. The simplicity of the `until` loop makes it easy to understand and maintain, contributing to more readable and robust shell scripts.

CAVEATS

If the condition never becomes true, the loop will run indefinitely. Always ensure your loop contains mechanisms for the condition to eventually be satisfied, such as updating variables within the loop body or external events.

EXIT STATUS

The exit status of the until command is the exit status of the last command executed in the loop body, or 0 if no commands were executed.

BREAK AND CONTINUE

The break and continue commands can be used within the until loop to alter its execution. break exits the loop prematurely, while continue skips the rest of the current iteration and proceeds to the next condition check.

HISTORY

The until command is a standard part of the POSIX shell specification and has been available since the early days of Unix. It's a core element in shell scripting languages like `sh`, `bash`, and `zsh`. Its primary design goal was to provide a simple and intuitive mechanism for creating loops based on the negation of a condition, complementing the `while` loop which executes as long as a condition is true.

SEE ALSO

while(1), for(1), if(1), test(1)

Copied to clipboard