while and until
Use while condition; do commands; done when work should repeat as long as a command succeeds (status 0). Use until condition; do commands; done to repeat while a command fails (nonzero status). The condition runs before each iteration, so either loop can run zero times. Unlike a word-list loop, the condition can depend on changing state. A counter, a successful input read, or another bounded condition can control repetition. Arrange for progress toward termination. An arithmetic comparison such as (( n <= 3 )) is a command that succeeds when the comparison is true. The final loop status is normally the last executed body command status, or zero when no body ran; it is not simply the final condition status. A nonzero condition status does not distinguish an ordinary false result from an error. When polling an external command, handle invalid input and other errors separately; use an explicit attempt limit.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Count upward
Expected stdout:
123Each update brings n closer to failing the condition.
Stop at a target
n=1until (( n == 4 )); do printf '%s\n' "$n" n=$(( n + 1 ))doneExpected stdout:
123The body stops when n reaches four.
A condition false at the start
n=5while (( n < 3 )); do printf '%s\n' unexpected n=$(( n + 1 ))doneprintf 'status=%s\n' "$?"Expected stdout:
status=0No iteration occurs, and the empty loop returns zero.
Common mistakes
Forgetting to update the counter can make a loop run forever. Do not copy unbounded polling loops into production; set a limit and handle failure.
Practice
Write a while loop printing 2, 4, 6, then an until loop producing the same sequence. Start with a value that already fails the while condition and confirm no output.
Next: Arithmetic for loops