for Loops in Bash

Su Suriya Ravichandran Updated 06 Dec 2026
13 min read ·Lesson 78 of 205

A loop repeats a group of commands. The for loop is the most common kind in Bash, and it is built around a simple idea: take a list of items, and run the same commands once for each item. Renaming a set of files, printing a report for every log, and calling a command on every argument of a script are all for loops. This lesson covers the list form of the loop, which walks through words. The counting form with an arithmetic header is the subject of lesson 79.

Syntax

for NAME in WORD1 WORD2 WORD3; do
    commands
done

The parts are:

  • for starts the loop and done ends it.
  • NAME is the loop variable. Bash assigns it a new value on every pass.
  • in is followed by the list, a series of words that Bash expands before the loop starts.
  • do begins the body, the commands that run once per word.
  • The semicolon before do is needed when do is on the same line as for. If do goes on its own line, the semicolon can be replaced by a newline.

Bash first expands the entire list, so that every brace expression, glob, variable and command substitution in it becomes plain words. Then it takes the words one at a time, copies each into the loop variable, and runs the body.

Basic Example

for fruit in apple banana cherry; do
    echo "I like $fruit"
done
echo "after the loop, fruit is still: $fruit"

Output:

I like apple
I like banana
I like cherry
after the loop, fruit is still: cherry

Understanding the Example

The list contains three words, so the body runs three times. On the first pass fruit is apple, on the second banana, and on the third cherry. After the last word has been used, the loop ends and the script continues with the next command.

The last line shows something that surprises many learners: the loop variable is not deleted when the loop finishes. It keeps the value from the last pass. A for loop does not create a separate scope, so the variable is an ordinary shell variable (lesson 34) that happens to be set by the loop.

The List of Words

The list is split into words by the normal shell rules, so quoting decides what counts as one item. A quoted string with spaces stays together:

for name in "Ana Maria" Bob "Chris D"; do
    echo "Hello, $name"
done

Output:

Hello, Ana Maria
Hello, Bob
Hello, Chris D

Without the quotes, Ana Maria would be two words and the body would run four times with Ana, Maria, Bob and so on.

A list can also be empty. In that case the body never runs, and the loop finishes without an error:

for x in; do echo "never"; done
echo "status of empty loop: $?"

Output:

status of empty loop: 0

An empty list happens naturally when a list comes from a command or a variable that turns out to hold nothing. It is not a failure, and the script simply continues.

Ranges with Brace Expansion

Typing every number by hand is tedious. Brace expansion (lesson 50) produces a sequence of numbers or letters, and it works well as a loop list:

for i in {1..5}; do echo -n "$i "; done; echo
for i in {5..1}; do echo -n "$i "; done; echo
for i in {0..20..5}; do echo -n "$i "; done; echo
for i in {a..e}; do echo -n "$i "; done; echo
for i in {01..05}; do echo -n "$i "; done; echo

Output:

1 2 3 4 5 
5 4 3 2 1 
0 5 10 15 20 
a b c d e 
01 02 03 04 05 

The form {start..end} counts up or down depending on the two numbers. A third number sets the step, as in {0..20..5}. Letters work as well, and a leading zero on the first number pads every value to the same width. The echo -n option suppresses the newline, so the numbers stay on one line, and the final plain echo ends the line.

Sequences can be mixed with ordinary words in one list:

for i in 1 5 {10..12} last; do echo -n "$i "; done; echo

Output:

1 5 10 11 12 last 

Variable Limits Need a Different Tool

Brace expansion happens before variables are expanded, so a variable cannot be used as the end of a range:

n=3
for i in {1..$n}; do echo "i=$i"; done

Output:

i={1..3}

The braces were not recognized as a range at that moment, and the loop received one word. The seq command, which is an external program and not part of Bash, expands the variable first and then counts:

n=3
for i in $(seq 1 $n); do echo "i=$i"; done
for i in $(seq 0 5 20); do echo -n "$i "; done; echo

Output:

i=1
i=2
i=3
0 5 10 15 20 

The call seq 0 5 20 takes the start, step and end in that order, which is different from the order in brace expansion. For loops whose limit comes from a variable, the arithmetic form in lesson 79 is usually the cleaner choice.

A running total is a typical use of a numeric loop. Arithmetic expansion (lesson 49) adds to the variable on every pass:

total=0
for i in {1..10}; do total=$((total + i)); done
echo "sum 1..10 = $total"

Output:

sum 1..10 = 55

Looping Over Files with Globs

A wildcard pattern in the list expands to the matching file names (lesson 52). This is the most common use of for in everyday scripts:

touch a.txt b.txt "my notes.txt" c.log
for f in *.txt; do echo "file: [$f]"; done

Output:

file: [a.txt]
file: [b.txt]
file: [my notes.txt]

The glob is expanded by the shell after word splitting is already settled, so a file name with a space stays as one item. That is why this form is safe with names such as my notes.txt, as long as the loop variable is quoted when it is used in the body:

for f in *.txt; do
    printf 'size of [%s]: ' "$f"; wc -c < "$f"
done

Output:

size of [a.txt]: 0
size of [b.txt]: 0
size of [my notes.txt]: 0

The quotes in "$f" keep my notes.txt as a single argument. Without them, wc would receive my and notes.txt as two separate files.

When a Pattern Matches Nothing

If no file matches, Bash leaves the pattern as it is. The loop then runs once with the literal text of the pattern:

for f in *.pdf; do echo "got: [$f]"; done

Output:

got: [*.pdf]

A script that goes on to open *.pdf would fail with a confusing error. There are two ways to protect against this. The first is to test that the item really exists, and skip it otherwise:

for f in *.pdf; do
    [ -e "$f" ] || continue
    echo "pdf: $f"
done
echo "guard done"

Output:

guard done

The continue command skips the rest of the body for that pass (lesson 84), so nothing is printed for the fake name. The second way is the nullglob option, which makes a pattern with no matches expand to nothing:

shopt -s nullglob
for f in *.pdf; do echo "got: [$f]"; done
echo "nullglob: loop ran zero times"
shopt -u nullglob

Output:

nullglob: loop ran zero times

The loop body ran zero times. The command shopt -u nullglob turns the option off again so that later commands in the script behave normally (lesson 149 covers shopt).

A pattern that ends with a slash matches only directories:

mkdir d1 d2
for d in */; do echo "dir: $d"; done

Output:

dir: d1/
dir: d2/

The loop variable can be reshaped with parameter expansion (lesson 54). This loop only prints the rename commands for each file, which is a safe way to check a plan before changing anything:

for f in *.txt; do echo "mv \"$f\" \"${f%.txt}.md\""; done

Output:

mv "a.txt" "a.md"
mv "b.txt" "b.md"
mv "my notes.txt" "my notes.md"

The expression ${f%.txt} removes the shortest match of .txt from the end of the value, and the new extension is then added by hand.

Looping Over Command Output

A command substitution can supply the list. Bash runs the command, then splits its output into words at spaces, tabs and newlines:

for w in $(echo "red green blue"); do echo "color $w"; done

Output:

color red
color green
color blue

Splitting happens on any whitespace, not only on line ends. A file that has two words on a line is turned into two items:

printf 'one two\nthree\n' > list.txt
for w in $(cat list.txt); do echo "[$w]"; done

Output:

[one]
[two]
[three]

This is harmless for simple word lists, but it breaks the moment items may contain spaces, which is common with file names and lines of text. For those cases, lessons 83 and 114 show how to read the output line by line with a while read loop. A for loop over $(ls) is a well-known trap for the same reason, and a plain glob such as for f in * does the job correctly.

Looping Over Script Arguments

The special parameter "$@" expands to all of the script's arguments, one word each (lesson 43). It is the standard list for a script that works on whatever files it is given:

#!/usr/bin/env bash
echo "number of arguments: $#"
for arg in "$@"; do
    echo "arg: [$arg]"
done

Running bash args.sh "two words" three "four five" printed:

number of arguments: 3
arg: [two words]
arg: [three]
arg: [four  five]

The quotes around "$@" preserve each argument as given, including the argument with two spaces. Without quotes, the arguments would be split again, and the result is a different list:

for arg in $@; do echo "split: [$arg]"; done

Output:

split: [two]
split: [words]
split: [three]
split: [four]
split: [five]

If the in part is left out completely, for uses the positional parameters automatically. The next loop is equivalent to the quoted version above:

for arg; do
    echo "same: [$arg]"
done

Output:

same: [two words]
same: [three]
same: [four  five]

Changing the Loop Variable

The loop variable is an ordinary variable, so the body can change it. The change affects only the rest of that pass, because the next pass assigns the next word again:

for i in 1 2 3; do i=$((i * 10)); echo "i=$i"; done

Output:

i=10
i=20
i=30

The list itself was fixed before the loop began, so changing i does not add or remove items.

The Exit Status of a for Loop

A for loop returns the status of the last command that ran in the body. If the body never ran, the status is 0:

for n in 1 2 3; do [ "$n" -lt 3 ] && echo "n=$n"; done
echo "loop status: $?"

for n in 1 2 3; do true; done; echo "loop status after true: $?"

Output:

n=1
n=2
loop status: 1
loop status after true: 0

In the first loop the test [ 3 -lt 3 ] failed on the final pass, so the whole loop reported 1. A script that relies on the status of a loop should therefore finish the body with a command whose status is meaningful, or record the status in a variable (lesson 117).

Redirecting and Piping a Loop

A whole loop acts like a single command, so its combined output can be redirected or piped. Redirections written after done apply to everything the loop prints:

for w in pear apple fig; do echo "$w"; done | sort
for i in 1 2 3; do echo "line $i"; done > out.txt
cat out.txt

Output:

apple
fig
pear
line 1
line 2
line 3

Here the loop output was sorted by the pipe, and in the second loop all three lines went into out.txt with one >, so the file was not rewritten on every pass.

A loop on the left side of a pipe runs in a subshell, as every pipeline stage does (lesson 61). Variables changed inside it are not visible afterward:

count=0
for i in 1 2 3; do count=$((count + 1)); done | cat
echo "count after piped loop: $count"

count=0
for i in 1 2 3; do count=$((count + 1)); done
echo "count after normal loop: $count"

Output:

count after piped loop: 0
count after normal loop: 3

The piped loop did its counting in a separate process, and the original count was never touched.

Skipping Items and Stopping Early

Two commands change the flow inside a loop. continue skips straight to the next item, and break leaves the loop completely. Lesson 84 covers them in depth, but a first look helps:

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

Output:

i=1
i=3

The value 2 was skipped with continue, and the loop was left at 4 with break, so 5 was never reached.

Practical Applications

This script reports the number of lines in every .log file of a folder. It uses a glob, a guard for the no-match case, parameter expansion to shorten the file name, and arithmetic expansion for the running total:

#!/usr/bin/env bash
# Report the number of lines in every .log file of a folder
dir=${1:-.}
total=0
for file in "$dir"/*.log; do
    [ -e "$file" ] || { echo "no .log files in $dir"; exit 1; }
    lines=$(wc -l < "$file")
    printf '%-16s %3d lines\n' "${file##*/}" "$lines"
    total=$((total + lines))
done
echo "total: $total lines"

For a folder logs with the files app.log (3 lines), error.log (2 lines) and web server.log (4 lines), the command bash report.sh logs printed:

app.log            3 lines
error.log          2 lines
web server.log     4 lines
total: 9 lines

The expression ${1:-.} means "the first argument, or the current folder if none is given" (lesson 45). The expression ${file##*/} removes everything up to the last slash, leaving only the file name. The file with a space in its name was handled correctly, because both the loop variable and the redirection target are quoted. On a folder without log files, the loop runs once with the literal pattern, the [ -e ] test fails, and the script prints no .log files in empty and stops.

Loops are also the natural way to create several related files:

for i in {1..3}; do
    echo "Chapter $i" > "chapter_$i.txt"
done

for f in chapter_*.txt; do
    echo "$f: $(cat "$f")"
done

for lang in Python Bash C; do
    echo "Learning $lang"
done | nl

Output:

chapter_1.txt: Chapter 1
chapter_2.txt: Chapter 2
chapter_3.txt: Chapter 3
     1	Learning Python
     2	Learning Bash
     3	Learning C

The first loop creates three files, the second reads them back by pattern, and the third sends its output through nl, which numbers the lines. Because the second loop uses the same pattern that the first loop's file names follow, it needs no list of names at all.

Portability

The for NAME in LIST; do ... done form is part of the POSIX shell language and works in every shell. The brace ranges are not. Dash does not perform brace expansion, so for i in {1..5} loops once with the literal text:

{1..5} 
{5..1} 
{0..20..5} 

A script that must run under sh should use seq, the arithmetic loop from lesson 79 (also a Bash feature), or a while loop with a counter (lesson 80). The seq command is separate software, so check that it exists on the systems you target. Lessons 188 and 189 compare Bash syntax with POSIX shell syntax in detail.

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 for Loops in Bash and get answers drawn from it.

Signed-in readers only.