break and continue

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 84 of 205

Normally a loop runs every iteration until its list is used up or its condition fails. The commands break and continue let the body of a loop change that course. break leaves the loop completely, and continue skips the rest of the current pass and moves on to the next one. They work in for, while and until loops (lessons 78 to 81) and make it possible to stop as soon as the answer is found or to ignore items that do not need processing.

break: Leave the Loop

for i in 1 2 3 4 5; do
    [ "$i" -eq 3 ] && break
    echo "i=$i"
done
echo "after loop i=$i"

Output:

i=1
i=2
after loop i=3

When i reaches 3, the test succeeds, the && runs break (lesson 65), and Bash jumps to the first command after done. The values 4 and 5 are never visited. The last line shows that the loop variable keeps the value it had when the loop was left.

continue: Skip to the Next Pass

for i in 1 2 3 4 5; do
    [ "$i" -eq 3 ] && continue
    echo "i=$i"
done

Output:

i=1
i=2
i=4
i=5

For i equal to 3 the continue command ended the current pass before the echo ran, and the loop went on with 4. Unlike break, the loop itself is not over.

The difference can be summed up in one line: break means "I am finished with the whole loop", while continue means "I am finished with this item".

Stopping When Something Is Found

The most common use of break is a search. Once you have found what you were looking for, there is no reason to examine the remaining items:

for f in alpha beta gamma delta; do
    if [ "$f" = gamma ]; then echo "found $f"; break; fi
    echo "checked $f"
done

Output:

checked alpha
checked beta
found gamma

The delta item was never checked. For long lists or slow checks, such as downloading something for each item, stopping early saves real time. The same pattern works when reading a file:

printf 'ana:1\nbob:2\ncy:3\n' > users.txt
while IFS=: read -r name id; do
    if [ "$name" = bob ]; then echo "bob has id $id"; break; fi
done < users.txt

Output:

bob has id 2

The loop reads lines until it finds the one for bob. The IFS=: setting splits each line at the colon (lesson 80).

Skipping Items with continue

The usual use of continue is to filter out items you do not want. This loop reads a configuration file and ignores blank lines and comments:

printf '# comment\n\nkeep one\n  # indented comment\nkeep two\n' > cfg.txt
while IFS= read -r line; do
    case "$line" in ''|'#'*|*[[:space:]]'#'*) continue ;; esac
    echo "setting: $line"
done < cfg.txt

Output:

setting: keep one
setting: keep two

The case statement (lessons 75 and 76) tests three patterns: an empty line, a line that starts with #, and a line whose # comes after a space or tab. If one of them matches, continue skips the echo. A guard like this keeps the main work of the loop at the same indentation level and avoids deeply nested if blocks.

The same idea handles missing files:

touch real.txt
for f in real.txt missing.txt; do
    [ -e "$f" ] || { echo "skip $f"; continue; }
    echo "processing $f"
done

Output:

processing real.txt
skip missing.txt

The braces group the echo and the continue, so that both run when the test fails.

continue in while Loops: Update the Counter First

In a for loop over a list, continue is always safe because the list moves forward by itself. In a while loop, the counter is changed by your code, and continue jumps over everything after it. If the update comes after the continue, the loop can get stuck. This loop is written correctly, with the update first:

i=0
while [ "$i" -lt 6 ]; do
    i=$((i + 1))
    (( i % 2 == 0 )) && continue
    echo "odd: $i"
done

Output:

odd: 1
odd: 3
odd: 5

The counter is increased before continue can skip the rest, so every pass makes progress. Now compare this version, where the update comes last and the continue runs when i is 1. A guard counter has been added so that the demonstration stops:

i=0; guard=0
while [ "$i" -lt 3 ]; do
    guard=$((guard + 1))
    [ "$guard" -gt 5 ] && { echo "guard stopped it"; break; }
    if [ "$i" -eq 1 ]; then continue; fi
    i=$((i + 1))
done
echo "i=$i guard=$guard"

Output:

guard stopped it
i=1 guard=6

When i became 1, continue skipped the i=$((i + 1)) line, so i stayed 1 forever. Without the guard this loop would never end (lesson 87). Whenever you use continue in a while or until loop, make sure the code that moves the loop forward runs before it.

continue in C-Style for Loops

The C-style loop from lesson 79 has its update step in the loop header, which makes it safe. continue still runs the update expression before the next test:

for (( i = 0; i < 6; i++ )); do
    (( i == 2 )) && continue
    echo -n "$i "
done; echo

Output:

0 1 3 4 5 

The value 2 was skipped, but i++ still ran, so the loop continued with 3.

Breaking Out of Several Loops

Both commands accept an optional number that says how many enclosing loops they apply to. The default is 1, the innermost loop. break 2 leaves the innermost loop and the loop around it:

for a in 1 2 3; do
    for b in 1 2 3; do
        if [ "$a" -eq 2 ] && [ "$b" -eq 2 ]; then break 2; fi
        echo "a=$a b=$b"
    done
done
echo "done"

Output:

a=1 b=1
a=1 b=2
a=1 b=3
a=2 b=1
done

At a=2 and b=2, break 2 ended both loops at once, so a=3 was never reached. With a plain break, only the inner loop would have ended and the outer loop would have gone on to a=3:

for a in 1 2 3; do
    for b in 1 2 3; do
        [ "$b" -eq 2 ] && break
        echo "a=$a b=$b"
    done
done

Output:

a=1 b=1
a=2 b=1
a=3 b=1

Each inner loop stopped at b=2, but the outer loop ran three times.

continue with a Number

continue 2 skips the rest of the current pass of the inner loop and of the outer loop's body, and starts the next pass of the outer loop:

for a in 1 2 3; do
    for b in 1 2 3; do
        [ "$b" -eq 2 ] && continue 2
        echo "a=$a b=$b"
    done
done

Output:

a=1 b=1
a=2 b=1
a=3 b=1

The output looks the same as the plain break version, because nothing follows the inner loop. The difference would show if the outer body had more commands after the inner loop: continue 2 would skip them, while a plain break would run them. Lesson 85 uses these numbers in nested loops.

Unusual Numbers

If you give a number larger than the number of enclosing loops, Bash simply leaves all of them:

for a in 1 2; do
    for b in 1 2; do
        break 5
    done
    echo "outer a=$a"
done
echo "after"

Output:

after

There are two loops, so break 5 ended both, and the echo "outer a=$a" line never ran. A number below 1 is an error. In Bash 5.2.21, break 0 printed an error message and the loop ended with status 1:

for a in 1; do break 0; echo "not reached"; done; echo "status: $?"

Output:

t84.sh: line 81: break: 0: loop count out of range
status: 1

The message begins with the name of the script and the line number, as the sandbox printed it for a script file. Typed interactively it begins with bash:.

Using break and continue Outside a Loop

They only make sense inside a loop. Elsewhere, Bash prints a warning and carries on with status 0:

break
echo "status: $?"

Output:

t84.sh: line 83: break: only meaningful in a `for', `while', or `until' loop
status: 0

The command continue behaves the same way. This often means a break was left behind after code was moved out of a loop. To leave a function, use return, not break.

break in a case Statement Inside a Loop

A case statement is not a loop, so a break inside it applies to the loop around it. This is the usual shape of a command loop that has a "quit" choice:

for cmd in start stop quit more; do
    case "$cmd" in
        quit) echo "quitting"; break ;;
        *) echo "handling $cmd" ;;
    esac
done

Output:

handling start
handling stop
quitting

The ;; still ends the quit clause, as in any case statement, even though the loop is left before it is reached. Lesson 86 uses the same structure for select menus.

Exit Status After break and continue

The status of a loop that ended with break is the status of the break command, which is 0:

for i in 1 2; do false; break; done
echo "status after break: $?"

for i in 1 2 3; do [ "$i" = 2 ] && break; done; echo "status: $?"
for i in 1 2 3; do true; done; echo "status: $?"

Output:

status after break: 0
status: 0
status: 0

The false before break did not matter. A loop left by break always reports success, so do not rely on the loop's status to learn whether the item was found. Set a variable before the break, or use a function with return, as shown next.

Returning from a Function Instead

When a loop is the main body of a function, return leaves the loop and the function in one step and carries a result:

find_first() {
    local x
    for x in "$@"; do [ "$x" -gt 10 ] && { echo "$x"; return 0; }; done
    return 1
}
find_first 3 8 12 20; echo "status $?"
find_first 1 2; echo "status $?"

Output:

12
status 0
status 1

The function prints the first number greater than 10 and returns 0, or returns 1 if there is none. The status therefore does tell the caller whether the item was found. Lessons 88 to 92 cover functions and local.

break in a Loop at the End of a Pipe

A loop on the right-hand side of a pipe runs in a subshell, as lesson 83 explained. break still stops the loop correctly, but variables set inside it do not reach the main script:

n=0
printf 'a\nb\nc\nd\n' | while read -r l; do
    n=$((n+1))
    [ "$l" = c ] && break
    echo "line $l"
done
echo "n outside pipe: $n"

Output:

line a
line b
n outside pipe: 0

The loop stopped at c, but n stayed 0 in the main shell. Use < <(command) or a redirection from a file when the main script needs the result.

break with an Intentional Infinite Loop

An infinite loop plus break is a standard way to express "keep going until something inside decides to stop":

n=0
while true; do
    n=$((n + 1))
    [ "$n" -ge 3 ] && break
done
echo "n=$n"

Output:

n=3

This form is useful when the exit test belongs in the middle of the body, not at the start. The next lessons on nested loops (85) and on infinite loops (87) build on it.

Portability

break, continue and their numeric forms are part of POSIX, so Dash handles them as Bash does:

#!/bin/sh
for a in 1 2 3; do
    for b in 1 2 3; do
        [ "$b" -eq 2 ] && continue 2
        echo "a=$a b=$b"
    done
done
for a in 1 2 3; do for b in 1 2 3; do [ "$a$b" = 22 ] && break 2; echo "$a$b"; done; done

Running this with Dash printed a=1 b=1, a=2 b=1 and a=3 b=1 for the first part, and 11, 12, 13 and 21 for the second. What does not carry over is the arithmetic test (( ... )) and the C-style for (( loop used in some examples above; use [ ] and a while loop for scripts that must run under sh (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 break and continue and get answers drawn from it.

Signed-in readers only.