for Loops in Bash
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:
forstarts the loop anddoneends it.NAMEis the loop variable. Bash assigns it a new value on every pass.inis followed by the list, a series of words that Bash expands before the loop starts.dobegins the body, the commands that run once per word.- The semicolon before
dois needed whendois on the same line asfor. Ifdogoes 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.