until Loops

Su Suriya Ravichandran Updated 06 Dec 2026
11 min read ·Lesson 81 of 205

An until loop repeats a block of commands until a condition becomes true. It is the mirror image of the while loop from lesson 80: a while loop keeps going as long as its condition succeeds, while an until loop keeps going as long as its condition fails. The moment the condition succeeds, the loop stops.

Both loops can express the same logic. The difference is readability. Some conditions are naturally phrased as "keep going while X is true" (while there are lines left), and others as "keep going until X happens" (until the file appears, until the server answers, until the counter reaches 10). Choosing the form that matches how you would say it aloud makes a script easier to read.

Syntax

until CONDITION; do
    commands
done

The CONDITION is an ordinary command, exactly as in an if statement (lesson 66). Before every pass, Bash runs it and looks at its exit status:

  • If the status is non-zero (failure), the body runs once, and then the condition is checked again.
  • If the status is 0 (success), the loop ends and the script continues after done.

Compare this with while, where the meaning of the two outcomes is swapped: while continues on status 0, until continues on a non-zero status. Like while, the condition is checked before the first pass, so the body can run zero times.

Basic Example

count=1
until [ "$count" -gt 3 ]; do
    echo "count=$count"
    count=$((count + 1))
done
echo "after: count=$count"

Output:

count=1
count=2
count=3
after: count=4

Understanding the Example

The condition is the test [ "$count" -gt 3 ] (lesson 73), which is true when count is greater than 3. Because this is an until loop, the body runs while that test is false:

  1. count is 1. The test fails, so the body runs and prints count=1, then adds 1.
  2. count is 2. The test fails again, so the body prints count=2.
  3. count is 3. The test still fails, so the body prints count=3.
  4. count is 4. The test succeeds, so the loop ends without printing 4.

The last line shows that count keeps its final value (4) after the loop, just like an ordinary variable. The body also updates count itself with arithmetic expansion (lesson 49). A loop body must change something the condition looks at, or the condition never changes and the loop never ends (lesson 87 covers this in detail).

Checked Before the First Pass

If the condition is already true at the start, the body never runs:

x=10
until [ "$x" -gt 5 ]; do echo never; done
echo "status: $?"

Output:

status: 0

Nothing was printed because 10 -gt 5 is true immediately. The status of a loop whose body never ran is 0. An until loop is therefore not a "do this at least once" loop. Bash has no do ... until form like some other languages; the condition always comes first.

Choosing Between until and while

The two loops are connected by negation. Any until loop can be rewritten as a while loop by reversing the condition with ! (lesson 74), and the other way around:

# until: keep going until the flag file exists
n=0
until [ -e done.flag ]; do
    n=$((n + 1))
    [ "$n" -eq 3 ] && touch done.flag
done
echo "flag appeared after $n passes"

# while: the same loop with the condition reversed
n=0
while ! [ -e done2.flag ]; do
    n=$((n + 1))
    [ "$n" -eq 3 ] && touch done2.flag
done
echo "while ! version: $n passes"

Output:

flag appeared after 3 passes
while ! version: 3 passes

Both loops behave identically. In the until version the condition reads naturally ("until the flag file exists"), while the while ! version requires the reader to mentally flip the meaning. That is the main reason until exists: it removes the !.

A useful rule of thumb is to look at the condition. If you would write a ! in front of it for a while loop, an until loop is usually clearer. If the condition is already positive (while [ "$i" -lt 10 ]), keep while.

Counting Down and Up

For counters, until works with both the test command and the arithmetic command (( )):

n=3
until (( n == 0 )); do echo -n "$n "; (( n-- )); done; echo liftoff

Output:

3 2 1 liftoff

The condition (( n == 0 )) succeeds when n equals 0. The body prints the value and decrements it. Because the loop ends the moment n is 0, the 0 itself is never printed. The (( n-- )) form is a Bash feature (see the portability section below); n=$((n - 1)) works everywhere.

Any Command Can Be the Condition

The condition is not limited to [ ]. Any command whose exit status carries a yes/no meaning works, including grep -q, ping, curl, test and your own functions. A common use is waiting for a message to appear in a log file. In this example, a background job appends the word READY to the file after one second, and the main script polls the file until it sees it:

printf 'one\ntwo\n' > log.txt
( sleep 1; echo "READY" >> log.txt ) &
tries=0
until grep -q READY log.txt; do
    tries=$((tries + 1))
    sleep 0.4
done
echo "found READY after $tries checks"

Output (the number of checks depends on timing):

found READY after 3 checks

The grep -q command prints nothing and returns 0 when it finds a match and 1 when it does not (lesson 21). The loop therefore keeps running while the word is missing and stops as soon as it appears. The short sleep between checks stops the loop from using the processor at full speed. The ( ... ) & part starts a background job (lesson 136); here it only simulates another program that is slow to finish.

A function can also serve as the condition, which is a clean way to give a complicated test a name:

tries=0
check() { tries=$((tries + 1)); [ "$tries" -ge 3 ]; }
until check; do echo "not yet ($tries)"; done
echo "check passed on try $tries"

Output:

not yet (1)
not yet (2)
check passed on try 3

The function's status is the status of its last command, the test. It fails twice and succeeds on the third call, which ends the loop. Notice that the condition itself has a side effect (it increments tries). This works, but keep such conditions short so that the loop remains easy to follow.

A Condition Made of Several Commands

The condition can be a list of commands. As in a while loop, the status of the last command in the list decides whether the loop continues:

a=0
until a=$((a+1)); [ "$a" -ge 3 ]; do echo "a=$a"; done
echo "final a=$a"

Output:

a=1
a=2
final a=3

Before each pass, Bash runs a=$((a+1)) and then the test. The assignment always succeeds, so only the test controls the loop. The update therefore happens inside the condition, and the body does not need one. This style is compact, but it hides the update, so it is usually clearer to put the counter change in the body.

Combining Conditions with || and &&

A very common real-world pattern is a bounded retry: keep trying until something works, but give up after a fixed number of attempts. With until, the condition says "stop when the work is done or when we have used all our attempts":

attempts=0
max=5
until [ -e ok.flag ] || [ "$attempts" -ge "$max" ]; do
    attempts=$((attempts + 1))
    echo "attempt $attempts"
    [ "$attempts" -eq 3 ] && touch ok.flag
done
if [ -e ok.flag ]; then echo "succeeded after $attempts attempts"; else echo "gave up"; fi

Output:

attempt 1
attempt 2
attempt 3
succeeded after 3 attempts

Here the file ok.flag stands for any successful result, and the line that creates it on the third attempt only simulates real work succeeding. The loop ends because the first part of the condition became true. If the file never appeared, the second part would end the loop after five attempts, and the final if would print gave up:

attempts=0
until [ "$attempts" -ge 3 ] || [ -e never.flag ]; do
    attempts=$((attempts + 1))
    echo "attempt $attempts"
done
[ -e never.flag ] || echo "gave up after $attempts attempts"

Output:

attempt 1
attempt 2
attempt 3
gave up after 3 attempts

The || operator (lesson 65) makes the condition succeed if either side succeeds. Always add an upper limit like this to any loop that waits for something outside the script's control. Without it, a missing file or an unreachable server makes the script wait forever. Lesson 142 shows the timeout command as another way to set a limit.

The Exit Status of an until Loop

An until loop returns the exit status of the last command that ran in its body, or 0 if the body never ran. The condition that finally ends the loop does not count:

i=0
until [ "$i" -ge 3 ]; do i=$((i + 1)); false; done
echo "status after body ending in false: $?"

i=0
until [ "$i" -ge 3 ]; do i=$((i + 1)); done
echo "status after normal end: $?"

y=9
until [ "$y" -gt 1 ]; do :; done
echo "status when body never ran: $?"

Output:

status after body ending in false: 1
status after normal end: 0
status when body never ran: 0

In the first loop the last body command was false, so the loop returned 1. This matters when a loop is the last command of a function or script, or when you test its status with if (lesson 66).

Reading Input Until a Condition Is Met

An until loop works well for asking a question until the user gives an acceptable answer. The important detail is what happens when the input runs out. Here is a loop that asks until it receives yes, and handles the end of the input explicitly:

answer=""
until [ "$answer" = yes ]; do
    read -r answer || { echo "input ended"; break; }
    echo "you typed: $answer"
done

Feeding it printf 'no\nmaybe\nyes\nextra\n' prints:

you typed: no
you typed: maybe
you typed: yes

Feeding it only printf 'no\nmaybe\n' prints:

you typed: no
you typed: maybe
input ended

The read command (lesson 31) fails at the end of the input. The || { ...; break; } part catches that failure and leaves the loop with break (lesson 84). Without it, read would keep failing, the answer variable would keep its last value, and the loop would run forever.

A related trap appears when read is placed inside the condition itself:

printf 'a\nb\n' > in.txt
cnt=0
until IFS= read -r line && [ "$line" = quit ]; do
    cnt=$((cnt+1))
    echo "body $cnt: [$line]"
    [ "$cnt" -ge 5 ] && { echo "stopped by safety limit"; break; }
done < in.txt

Output:

body 1: [a]
body 2: [b]
body 3: []
body 4: []
body 5: []
stopped by safety limit

The file has no line quit, so after the second line read fails, which makes the condition fail, and an until loop continues when its condition fails. The loop would run forever on an empty variable if the safety limit were not there. For reading lines until the end of input, use while read (lesson 80). Use until for reading only when the stopping condition is a value you check yourself.

Processing Arguments with shift

The test [ $# -eq 0 ] is true when no arguments are left, so an until loop can walk through the positional parameters with shift (lesson 44):

set -- a b c
until [ $# -eq 0 ]; do echo "arg $1"; shift; done

Output:

arg a
arg b
arg c

The loop runs until no arguments remain. The same loop with while [ $# -gt 0 ] is just as common; the choice is a matter of reading preference.

Infinite Loops with until

A condition that never succeeds gives a loop that runs until the body leaves it. The command false always fails, so until false is the mirror of while true:

n=0
until false; do
    n=$((n+1))
    [ "$n" -ge 3 ] && break
done
echo "left with n=$n"

Output:

left with n=3

This form is legal, but most scripts write while true for an intentional infinite loop, because "while true" is easier to read than "until false". Lesson 87 covers how to write such loops safely.

Portability

The until ... do ... done structure, the test command [ ], and arithmetic expansion $(( )) work in every POSIX shell, including Dash:

#!/bin/sh
i=1
until [ "$i" -gt 3 ]; do
    echo "i=$i"
    i=$((i + 1))
done

Running this with Dash prints i=1, i=2 and i=3. The arithmetic command (( )) used in the countdown earlier is a Bash feature and is not available in Dash, so scripts meant for sh should use [ "$n" -eq 0 ] and n=$((n - 1)) instead (see lessons 188 and 189).

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about until Loops and get answers drawn from it.

Signed-in readers only.