A bash until loop runs its body repeatedly as long as the test condition is false, and stops the moment that condition becomes true. That is the single fact that separates it from while, which does the opposite. You write until condition; do commands; done, and the condition is re-evaluated from scratch before every pass. If the condition is already true the first time bash checks it, the loop body never executes at all. Everything below builds on that one inverted rule, because almost every real mistake with until comes from writing a while condition out of habit and getting a loop that either never starts or never ends.

How until Differs From while in One Line of Reasoning

while continues while the test succeeds; until continues while the test fails. That sounds cosmetic, but it changes which expression reads naturally. Use until when your mental model is "keep going until this becomes true" — a service answering, a file appearing, a counter reaching a ceiling. Use while when the model is "keep going while this remains true" — reading lines from a stream, processing remaining arguments.

The condition is any command or compound test, and bash judges it purely by exit status: zero means true, non-zero means false. That means until grep -q pattern file; do ... works exactly like a test, and so does a whole pipeline's trailing status. Here is the smallest side-by-side that shows the inversion clearly:

The loop keeps running while n is five or less — that is, while [ "$n" -gt 5 ] is false. On the pass where n becomes 6, the test is true and bash exits before echoing. Expect output 1 through 5.

A while [ "$n" -le 5 ] version produces identical output. Both are fine; the choice is readability. When the terminating condition is a single clean predicate like "file exists" or "port is open", until usually wins because the condition states the goal rather than its negation.

Prerequisites Before You Type Any Loop

Nothing exotic is needed. You want:

A bash shell, version 3.2 or newer. macOS ships 3.2 as /bin/bash; most Linux distributions ship 4.x or 5.x. Check with bash --version. A scratch directory you can write to, so a runaway loop cannot fill a real path. mkdir -p /tmp/looplab && cd /tmp/looplab is enough. For the retry examples, a command whose failure you can trigger on purpose — a curl against a host you know is unreachable, or a small script that exits non-zero a few times.

Run the snippets interactively first. A loop you can watch is a loop you can debug.

Step-by-Step: Build Your First Loop and Prove It Terminates

1: Set a counter and write the until header with a numeric test: n=0. 2: Put the work inside: echo "attempt $n". 3: Increment inside the body: n=$((n + 1)). 4: Close with done and run it. You should see four lines for n=0 through n=3 if the test is [ "$n" -ge 4 ]. 5: Verify termination by timing it: wrap the loop in time ( ... ) or run echo done after done. If done prints, the loop ended.

For the retry version, the order shifts slightly:

1: Decide the maximum attempts and the sleep interval before writing anything. Write them as variables at the top: max=5, sleep_s=2. 2: Start the counter at 1. 3: Put the command whose failure you expect inside a if test, and treat success as the loop's exit condition via break. 4: Sleep between attempts, then increment. 5: After the loop, check whether the counter exceeded max and print a failure message if so.

That five-step version — attempt, test, break on success, sleep, increment — is the shape of nearly every production retry loop. The success check is literal: run it against a command you know succeeds and confirm the loop exits on the first pass with no sleep. The failure check is the opposite: point it at something unreachable and confirm it stops after exactly max attempts rather than hanging.

Example Set: Six Patterns You Will Actually Reuse

Each of these is short enough to paste into a terminal. Read the comment first; the comment is the point.

Fixed range counter. until (( n >= 10 )); do ... n=$((n+1)); done. Use arithmetic evaluation (( )) — it is cleaner than [ ] for numbers and returns status directly.

Wait for a file to appear. until [ -f /tmp/ready.flag ]; do sleep 1; done; echo "flag seen". Test the loop by touching the file in another terminal. Success is the prompt returning; failure is silence forever, which is why you add a timeout.

Wait for a port to accept connections. until nc -z 127.0.0.1 8080; do sleep 1; done. nc -z exits zero when the TCP connection opens. If nc is unavailable, bash -c "/dev/null 2>&1; do attempts=$((attempts+1)); [ "$attempts" -ge 5 ] && { echo "gave up"; break; }; sleep 2; done. Note curl -f — without it, an HTTP 500 still returns exit 0 and your retry loop never fires. That is a real trap: the loop "succeeds" on the first try while doing nothing useful.

Read a file written by another process. until grep -q '^EXIT=' /tmp/run.log 2>/dev/null; do sleep 1; done. Redirect stderr because grep complains loudly while the file does not yet exist, and that noise makes logs unreadable.

Block until a background job finishes, without wait. until [ "${doneflag:-0}" -eq 1 ]; do sleep 1; done where a worker sets doneflag through a shared file or a named pipe. wait is usually better; this pattern exists because some supervisors give you no process handle.

Every one of these is a busy-ish poll. They are correct, and on any modern machine sleeping one second inside a loop costs nothing measurable. Do not sleep in the hundredths of a second trying to be clever.

How to Write a Timeout So a Broken Condition Cannot Hang You

An external condition that never becomes true will hang until forever. The fix is a bounded loop: count attempts and break when you cross the limit.

Total wait under the worst case is very close to max seconds: the file check runs immediately on entry, then once after each sleep, so the window is max checks and max-1 sleeps if you sleep after the increment — check your own ordering and the numbers move by one second. With max=30 and one-second sleeps, the loop gives up at roughly 30 seconds. Choosing that number is a judgment call, not a universal constant: local file watchers usually get 5–10 seconds, a remote service in a deploy script 60–120 seconds, and anything involving DNS propagation or certificate issuance is a job for a proper watcher rather than a shell loop.

Notice the loop also exit 1s rather than falling through. Falling through with a message leaves the script's exit status at zero and downstream automation thinks the step succeeded. If you need to continue instead of exit, use break and record a failure flag.

What Happens on the First Pass (and the Zero-Iteration Edge)

until evaluates the condition before running the body. If the condition is true on entry, the body runs zero times.

Prints only after. The same applies to until [ -e /nonexistent ]; do ... resulting in one or more passes, versus until [ -e /etc/hostname ]; do ... on a machine where that file exists, which runs zero passes.

This is the most common surprise when converting a for loop: readers expect "do it at least once". If you need at-least-once semantics, that is a while/do-while shape in bash — either write the first action before the loop and then loop on the condition, or use until false; do ...; break-when-done. Do not add a fake first iteration inside an until just to force one pass; it obscures the logic.

Zero iterations are usually desired. "Wait until the stop file exists" should not touch anything if the stop file is already there. Treat the zero-pass case as a correctness feature and test it explicitly, because it is the case that breaks when you invert a condition by hand.

Loop Control: break, continue, and Exit-Status Discipline

break leaves the loop immediately; continue jumps to the next condition check. They work the same in until as in while and for.

Prints odd numbers 1, 3, 5, 7, 9.

The discipline part matters more than the commands. A loop's exit status is the status of the last command executed in the body. If you end a body with an echo, the loop returns zero and callers cannot tell it failed. Either exit explicitly, break with a flag, or make the final statement the thing whose status you care about. And if you are running under set -e, be aware that until condition; do ... is exempt from set -e for the condition itself — the condition returning non-zero is exactly what keeps the loop going, so the header will not kill the script. Commands inside the body are not exempt.

Reading and Writing Files Inside an until Loop

You can pipe into an until loop, but the loop then runs in a subshell, and any variable you set inside it disappears when the loop ends. That single fact causes more silent bugs than any other in shell scripting.

This works — the redirect is on done, so the loop runs in the current shell and count survives. The piped form, cat data.txt | until ... read ..., does not: the final echo prints 0. When you need both a pipeline and the resulting variables, restructure to a process substitution (done < <( ... )) so the loop stays in your shell.

Also guard read with || break in until code the way you would for while read. In a while read loop the condition handles end-of-file naturally; in until false-style loops the read itself must be the exit condition, or you get one extra pass with an empty line.

Arithmetic and Duration Checks That Avoid Floats

Bash arithmetic is integer-only. until (( t >= 2.5 )) is a syntax error. Sleep-aware loops therefore use whole seconds, or convert to milliseconds.

$SECONDS is a bash built-in that ticks once per second. The subtraction above is integer arithmetic, so 5 is exact and anything under a second rounds to zero. If you need sub-second timing, use date +%s%N and compare nanoseconds, or reach for timeout and skip the loop entirely.

For counting down a fixed number of attempts, arithmetic until is cleaner than comparing strings: until (( tries++ >= 3 )) has a side effect inside a test, which is legal but hard to read. Prefer an explicit increment in the body.

Debugging Loops That Never End or Never Start

Symptoms point at causes. Split the diagnosis accordingly.

Symptom Likely cause Reversible check
Loop never runs Condition already true on entry (until vs while inversion) echo $? after running the condition alone
Loop runs forever Condition can never become true Add echo of the tested value each pass, run 3 iterations, inspect
Loop runs once then stops break hit on first pass, or condition inverted inside the body Search the body for break and exit
Counter never advances Body runs in a subshell (pipeline, command substitution) Replace pipe with redirect on done
Retry never fires Command returns 0 on failure (e.g. curl without -f) Run the command against a known-failing target and echo $?
Script exits early set -e and an unguarded failing command in the body Run with bash -x script.sh

The two checks that resolve most cases: run the condition by itself and print $?, and run bash -x on the script for three or four iterations. The trace shows the condition's evaluation and exit status on every pass, which is the whole story.

Stop and get help rather than force-fitting a loop when you find yourself chaining three or more nested untils, or when the loop's work involves making changes that are hard to undo. The shell is the wrong tool at that point; a small script in a general-purpose language, or a systemd unit with Restart=, manages this class of problem with far less risk.

until Against the Alternatives: A Decision Table

Approach Best for Fails you when
until loop Waiting for a positive condition with a clear predicate Condition never becomes true and you forgot the timeout
while loop Iterating while something remains true (streams, counters) You invert the condition by mistake and it never starts
for loop Known list or range The list is unknown in advance
timeout N cmd Bounding one command's runtime You need retries, not a single hard limit
retry/until wrapper in the program itself Service startup ordering You are reinventing it in shell

A fair comparison on one dimension — total complexity: for a single "wait for file", timeout 30 bash -c 'until [ -f /tmp/x ]; do sleep 1; done' is the same instruction count as the loop plus its timeout counter, and harder to read. For a "retry five times then give up", the hand-written until loop above is shorter than composing timeout with a retry helper. Pick the smaller one for the job in front of you.

One real drawback worth naming: until loops that poll files cannot see a file being written — they only see "exists" or "matches". If the producer creates the file first and writes to it over several seconds, [ -f file ] becomes true immediately and your loop proceeds to read a half-written file. Wait for a sentinel the producer writes last, or for a size or pattern check, rather than for mere existence.

Frequently Asked Questions

Does until run the body at least once? No. The condition is checked first, so an initially-true condition means zero iterations. Use a first explicit action before the loop when you need one guaranteed pass.

Can the condition be a function? Yes, if it returns an exit status: until is_ready; do sleep 1; done. Keep the function's return values honest — zero for ready, non-zero for not.

Why does my loop lose variables when I pipe into it? Piping puts the loop in a subshell, so assignments vanish. Move the redirect onto done or use process substitution.

How do I exit an until loop from inside a nested if? break exits the innermost loop; break 2 exits two levels. return from a function also exits the loop and the function at once.

Does until work in sh as well as bash? /bin/sh (dash on Debian/Ubuntu) supports until and [ ] tests. Arithmetic (( )), [[ ]], and $SECONDS are bash extensions; if the script must run under sh, keep to [ ] and expr.

Used with a bounded attempt count and an explicit failure branch, the until loop is the shortest correct way to express "wait for this to become true, but not forever" in a shell script. Write the condition as the goal, not its negation, and the loop usually reads as plainly as the sentence you'd say out loud.