Coding

Bash For Loop: Syntax and Examples (Lists, Ranges, Files)

A bash for loop repeats a block of commands once for each item in a list: for name in item1 item2 item3; do commands; done. Bash also has a C-style form, for ((i = 0; i < 5; i++)); do commands; done, for counting.

for name in alice bob carol; do
  echo "Hello, $name"
done

Example output:

Hello, alice
Hello, bob
Hello, carol

The rest of this page covers each way to build the list, how to control the loop, and the mistakes that cause most for-loop bugs. For the wider picture of writing scripts, see bash script basics.

Bash for loop syntax

The bash manual gives the form as for name [ [ in word ... ] ; ] do list ; done. Bash expands the words after in, then runs the commands between do and done once per resulting word, with the variable set to that word. You can put do on its own line instead of after the semicolon:

for name in alice bob
do
  echo "$name"
done

The return status of the loop is the exit status of the last command that executed.

Loop over a list of words

Write the items directly. Quote any item that contains a space, or bash splits it into two:

for city in "New York" Paris Tokyo; do
  echo "$city"
done

To keep a list in a variable and still handle spaces correctly, use an array and expand it with "${cities[@]}":

cities=("New York" Paris Tokyo)
for city in "${cities[@]}"; do
  echo "$city"
done

Arrays are a bash feature, not POSIX sh. A plain variable such as cities="New York Paris" expanded as $cities gets split on whitespace into three words: New, York and Paris.

Loop over a range of numbers

Brace expansion produces a sequence. The bash manual describes it as x..y[..incr]:

for i in {1..5}; do echo "$i"; done        # 1 2 3 4 5
for i in {0..20..5}; do echo "$i"; done    # 0 5 10 15 20
for i in {01..03}; do echo "$i"; done      # 01 02 03

When either end starts with a zero, the manual says each generated term contains the same number of digits, zero-padding where necessary. That is how {01..03} gives 01 02 03.

Variables do not work inside the braces. The manual states that brace expansion is performed before any other expansions, so {1..$n} is not expanded as a range. Use the C-style loop when the end is a variable.

C-style for loop: for ((i = 0; i < n; i++))

n=4
for ((i = 1; i <= n; i++)); do
  echo "step $i of $n"
done

Example output:

step 1 of 4
step 2 of 4
step 3 of 4
step 4 of 4

The three expressions are arithmetic: initialise, test, update. Inside (( )) you don't need $ before variable names. Per the manual, if any expression is omitted it behaves as if it evaluates to 1, so for ((;;)); do ...; done is an infinite loop that you leave with break.

Loop over files

Let the shell expand a glob. Do not parse the output of ls.

for file in *.log; do
  echo "processing $file"
done

Quote "$file" wherever you use it. A file called my notes.log is one item from the glob, but unquoted $file in a later command is split into two words.

Two more patterns:

# Rename every .txt file to .md
for file in *.txt; do
  mv -- "$file" "${file%.txt}.md"
done

# Files in subdirectories (bash 4+; run shopt -s globstar first)
shopt -s globstar
for file in **/*.log; do
  echo "$file"
done

${file%.txt} removes the shortest match of .txt from the end of the value. The -- after mv stops a file name that starts with a dash being read as an option.

The glob that matches nothing

If no file matches, bash leaves the pattern as a literal word by default, and the loop runs once with file set to the text *.log:

$ for file in *.log; do echo "got: $file"; done
got: *.log

This is example output from a directory with no .log files. Either test inside the loop with [ -e "$file" ] || continue, or run shopt -s nullglob first so that an unmatched pattern expands to nothing and the loop body never runs.

File names with newlines or odd characters

A glob handles every legal file name, including ones with spaces. When you need find to choose the files, use -print0. The find manual says it prints the name followed by a null character, which allows names containing newlines or other white space to be interpreted correctly. Read them back with a while loop:

while IFS= read -r -d '' file; do
  echo "found: $file"
done < <(find . -name '*.log' -print0)

read -d '' splits on the null character instead of newline, and -r stops backslashes being treated as escapes.

Loop over command output, lines and arguments

Lines of a file. Use while read, not for line in $(cat file). The for version splits on every space, not on every line:

while IFS= read -r line; do
  echo "line: $line"
done < input.txt

Script arguments. With no in clause, the manual says the loop executes once for each positional parameter that is set, so these two loops are equivalent:

for arg; do echo "$arg"; done
for arg in "$@"; do echo "$arg"; done

The second form is clearer to a reader, so prefer it.

Output of a command. for user in $(cut -d: -f1 /etc/passwd) works only because user names contain no spaces. Anything whose output may contain spaces should go through while read instead.

break and continue

  • continue resumes the next iteration of the enclosing for, while, until or select loop.
  • break leaves the loop. break 2 leaves two nested loops. If the number is greater than the number of enclosing loops, all enclosing loops are exited.
for i in {1..10}; do
  if (( i % 2 == 0 )); then continue; fi   # skip even numbers
  if (( i > 7 )); then break; fi           # stop after 7
  echo "$i"
done

Example output: 1, 3, 5, 7, each on its own line.

for vs while vs until

LoopRuns whileUse it for
for x in listitems remain in the listKnown words, files, arguments, ranges
for ((i=0; i<n; i++))the arithmetic test is trueCounting with a variable limit
while commandthe command exits with status 0Reading lines, retrying, waiting
until commandthe command exits non-zeroWaiting for something to become true

The manual defines until as identical to while except that the test is negated.

Common for-loop mistakes

  • Unquoted variables. rm $file with file="my notes.txt" runs rm on two names. Write rm -- "$file".
  • {1..$n} does nothing useful. Brace expansion runs first. Use for ((i = 1; i <= n; i++)).
  • Looping over $(ls). It splits on spaces. Use a glob.
  • Missing done or do. Bash reports a syntax error such as syntax error: unexpected end of file, usually at the end of the script and not at the loop that is wrong. Check that every for has a matching do and done.
  • Running a bash loop under sh. {1..5} and ((...)) loops are not POSIX. On Debian and Ubuntu, sh is dash, so use bash script.sh or a #!/usr/bin/env bash shebang.

Frequently asked questions

What is the difference between a bash for loop and a while loop?
A for loop runs its body once for each item in a list, or while a counter condition holds in the C-style form. A while loop runs its body for as long as a command succeeds, meaning it exits with status 0. Use for when you have a known set of items, and while when you read input line by line or wait for a condition.
How do I loop from 1 to a variable in bash?
Brace expansion happens before variable expansion, so {1..$n} does not work. Use the C-style loop instead: for ((i = 1; i <= n; i++)); do ...; done. Alternatively run seq 1 "$n" in a command substitution, which splits on whitespace.
How do I exit a bash for loop early?
Use break to leave the loop immediately, or break 2 to leave two nested loops. Use continue to skip the rest of the current iteration and start the next one. If n is greater than the number of enclosing loops, break exits all of them.
Does the bash for loop work in sh?
The list form (for x in a b c) is part of POSIX sh. The C-style form (for ((i=0; i<3; i++))) and brace ranges like {1..5} are bash features, and fail under dash, which is /bin/sh on Debian and Ubuntu.

Sources