Avoiding Infinite Loops

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

An infinite loop is a loop whose condition never becomes false (for while) or never becomes true (for until), so the loop never ends by itself. In a script this usually looks like a program that hangs: the terminal prints the same line again and again, or prints nothing while one CPU core runs at full speed.

Some infinite loops are written on purpose, such as a service that waits for work forever, and they always contain a planned way out. The ones to avoid are the accidental ones. This lesson shows the typical causes, how to recognize them, how to stop a running loop and how to write loops that cannot get stuck.

How a Loop Gets Stuck

A while loop (lesson 80) runs the body as long as the condition command succeeds. If nothing in the body changes what the condition tests, the result is the same on every pass, and the loop continues forever. Every accidental infinite loop is one of a few patterns.

The counter is never updated

i=1
while [ "$i" -le 3 ]; do
    echo "i is $i"
done

The condition tests i, but the body never changes i. The output would never stop:

i is 1
i is 1
i is 1
i is 1
i is 1
...

To show it safely here, the loop was cut with | head -n 5. After five lines head exits, and the loop is stopped by a signal when it writes to the closed pipe (the pipeline status was 141 0, where 141 is 128 plus the signal number 13). The fix is to add i=$((i + 1)) inside the loop (lesson 49).

The step skips the target value

n=0
while [ "$n" -ne 10 ]; do
    n=$((n + 3))
done

The values of n are 3, 6, 9, 12, 15, 18, and so on. The loop waits for the value 10, but n jumps over it, so n -ne 10 stays true forever. In a test with a safety limit, n had reached 18 after six passes and the loop had not ended.

The cure is to compare with a range test instead of an exact value:

n=0
while [ "$n" -lt 10 ]; do
    n=$((n + 3))
done
echo "n=$n"
n=12

The same problem hits until. This loop counts down by 2 from an odd number and never meets 0:

n=5
until [ "$n" -eq 0 ]; do
    n=$((n - 2))
done

The values are 3, 1, -1, -3, and so on. After five passes, a test with a limit showed n=-5. Writing the condition as until [ "$n" -le 0 ] ends the loop (n=-1 at the end), because -le accepts every value at or below zero.

continue skips the update

A continue (lesson 84) that runs before the counter update sends the loop back to the condition with the same value:

i=0
while [ "$i" -lt 5 ]; do
    if [ "$i" -eq 2 ]; then
        continue
    fi
    echo "i=$i"
    i=$((i + 1))
done

The loop prints i=0 and i=1, and then it sticks at i=2 forever, because the continue jumps back to the condition before the update line is reached. A test with a guard counter confirmed this and had to stop the loop by itself. The fix is to update the counter first, before any continue:

i=0
while [ "$i" -lt 5 ]; do
    i=$((i + 1))
    [ "$i" -eq 3 ] && continue
    echo "i=$i"
done
i=1
i=2
i=4
i=5

A state that never changes

status=running
while [ "$status" != "done" ]; do
    :
done

Here the loop waits for a variable to change, but nothing in the shell changes it. A variable only changes when the loop (or something it calls) assigns to it. If you are waiting for something outside the script, such as a file or a service, the loop must check that outside thing on each pass, for example with [ -e file ] or a command such as curl, instead of reading a variable that stays the same.

Reading input that has ended

This loop looks harmless:

while true; do
    read -r line
    echo "got [$line]"
done < in.txt

When in.txt holds the lines a and b, the loop prints them, and then it continues forever. At the end of the file read fails, but nobody looks at its status, so the loop goes on with an empty line. A version with a guard counter printed

got [a]
got [b]
got []
got []
got []
stopped by guard

The fix is to leave the loop when read fails:

while true; do
    read -r line || break
    echo "got [$line]"
done < in.txt

or, simpler, to let read be the condition:

while read -r line; do
    echo "got [$line]"
done < in.txt

Both versions print got [a] and got [b] and then stop. The second form is the standard way to read a file line by line (lessons 80 and 114).

Spotting a Stuck Loop with set -x

When a loop hangs and the reason is not clear, turn on tracing for the loop. set -x makes Bash print every command, with the values of the variables already expanded (lesson 126 covers it in detail):

i=1
guard=0
set -x
while [ "$i" -le 3 ]; do
    guard=$((guard + 1))
    [ "$guard" -ge 3 ] && break
done
set +x
+ '[' 1 -le 3 ']'
+ guard=1
+ '[' 1 -ge 3 ']'
+ '[' 1 -le 3 ']'
+ guard=2
+ '[' 2 -ge 3 ']'
+ '[' 1 -le 3 ']'
+ guard=3
+ '[' 3 -ge 3 ']'
+ break
+ set +x

Every condition check shows 1 -le 3. The value of i never changes, so the trace makes the cause visible within a few lines. The guard counter in this example only exists to stop the demonstration after three passes.

Stopping a Loop That Is Already Running

Ctrl + C

In an interactive terminal, Ctrl + C sends the interrupt signal (SIGINT) to the running script, and the script ends. The shell then shows the prompt again. A script that was stopped this way normally returns a status of 130 (128 plus the signal number 2).

The kill command

If the script runs in the background or in another terminal, find its process ID and send it a signal (lessons 139 and 140):

bash stuck.sh &
pid=$!
kill "$pid"
wait "$pid"
echo "status after kill: $?"
status after kill: 143

The default signal of kill is SIGTERM, number 15, so the status is 128 + 15 = 143. If a program ignores SIGTERM, kill -9 "$pid" (SIGKILL) ends it without giving it a chance to clean up, so use it only as a last step.

Cleaning up when a loop is stopped

A loop that creates temporary files or lock files should remove them when it is interrupted. The trap command (lesson 123) runs a command when the script receives a signal:

trap 'echo "terminated, cleaning up"; exit 143' TERM
while true; do sleep 0.1; done

Started in the background and ended with kill, the script printed

terminated, cleaning up
status: 143

The trap command runs first, then the script exits with the status it was told to use. The same works for INT, the signal behind Ctrl + C. (A background job started with & in a non-interactive shell ignores SIGINT, so this example uses TERM, which can be tested from a script.) Lesson 141 explains interrupt handling in more detail.

Writing Loops That Always End

The best protection is to build a limit into every loop that waits for something outside your control.

A maximum number of attempts

max=5
attempt=0
until [ -e ready.flag ]; do
    attempt=$((attempt + 1))
    if [ "$attempt" -ge "$max" ]; then
        echo "giving up after $attempt checks"
        break
    fi
done
giving up after 5 checks

When ready.flag never appears, the loop makes five checks and then leaves. The break is in the body, so the loop ends in one of two ways: the condition becomes true, or the attempt limit is reached. After the loop, test [ -e ready.flag ] once more if the script must know which of the two happened.

The same limit can be placed in the condition, which keeps all the rules in one place:

tries=0
until [ -e never.flag ] || [ "$tries" -ge 3 ]; do
    tries=$((tries + 1))
    echo "try $tries"
    sleep 0.1
done
[ -e never.flag ] || echo "never.flag still missing after $tries tries"
try 1
try 2
try 3
never.flag still missing after 3 tries

The sleep between the checks matters. A loop that checks a file thousands of times per second wastes CPU time, while a short pause gives the other program time to do its work.

A time limit with SECONDS

Bash keeps a variable called SECONDS that counts the seconds since the shell started. It lets you set a deadline instead of counting attempts:

( sleep 1; touch ready.flag ) &
deadline=$((SECONDS + 5))
while [ ! -e ready.flag ]; do
    if [ "$SECONDS" -ge "$deadline" ]; then
        echo "timed out"
        break
    fi
    sleep 0.2
done
[ -e ready.flag ] && echo "ready file appeared"
wait
ready file appeared

The background subshell creates the file after one second, so the loop ends well before the five-second deadline. When the file never appears, the loop prints timed out and leaves. A second test, with a 2-second limit and no file, printed timed out after 2s. SECONDS is a Bash feature; a portable script can use date +%s instead (lessons 188 and 189).

The timeout command

If you cannot change the script that gets stuck, run it under timeout (lesson 142), which ends a command after a number of seconds:

timeout 1 bash stuck.sh
echo "timeout status $?"
timeout status 124

The status 124 means that the time limit was reached and timeout stopped the command. This protects a scheduled script that might otherwise run for days.

Infinite Loops Written on Purpose

A long-running script, such as a watcher or a small server, is a loop that should not end by its condition. Bash gives several equivalent ways to write it:

while true; do ...; done
while :; do ...; done
for (( ; ; )); do ...; done

true and : are both commands that always succeed (lesson 80). The C-style form with three empty parts (lesson 79) has no condition at all, which means "always continue". In each case, a normal exit must be planned with break, return or exit:

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

The other two forms ended at n=2 (while :) and n=4 (for (( ; ; ))) with the same kind of break. A deliberate infinite loop should also contain a sleep or a blocking command such as read, so that it does not use a whole CPU core while it waits.

Portability

The while, until, break and [ ] constructs shown here work in any POSIX shell. A Dash test confirmed that while :, until [ "$i" -ge 3 ] and $(( )) give the expected results. The C-style for (( ; ; )) form does not exist in Dash and fails with

d87.sh: 7: Syntax error: Bad for loop variable

Use while : in scripts that must run under sh. SECONDS, sleep 0.2 with a fractional value and timeout are not guaranteed everywhere: SECONDS is a Bash feature, and a fractional sleep works with GNU coreutils but not with every sleep program.

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 Avoiding Infinite Loops and get answers drawn from it.

Signed-in readers only.