ZetCode

Bash Loops

last modified October 24, 2026

Loops repeat commands: for each file in a directory, for each line of a file, for a range of numbers, or until a condition changes. Bash has for, while, and until loops, plus select for simple menus. Most loop problems in practice come from word splitting and from reading input, so this article covers those pitfalls along with the syntax.

The examples were run with Bash 5.2 on Debian 12. In the transcripts, > at the start of a line is the shell's prompt for the continuation of a command that spans several lines.

Looping over a list

The for loop assigns each word of a list to a variable and runs the body for it.

for color in red green blue; do
    echo "color: $color"
done
for word in one two three; do echo "$word"; done

The body lies between do and done. On one line, the parts are separated with semicolons.

$ for color in red green blue; do
>     echo "color: $color"
> done
color: red
color: green
color: blue
$ for word in one two three; do echo "$word"; done
one
two
three

Looping over files

A glob pattern in the list expands to the matching file names. This is the correct way to loop over files.

for f in photos/*.jpg; do
    echo "processing $f"
done
for f in photos/*.png; do echo "processing $f"; done
shopt -s nullglob
for f in photos/*.png; do echo "processing $f"; done
shopt -u nullglob

Each file name is one word, even old town.jpg with its space, as long as $f is quoted inside the loop. When nothing matches, Bash leaves the pattern as it is, and the loop runs once with the literal string photos/*.png. The nullglob option makes a pattern without matches expand to nothing, so the loop does not run at all. Alternatively, check [ -e "$f" ] || continue at the start of the body.

$ for f in photos/*.jpg; do
>     echo "processing $f"
> done
processing photos/beach.jpg
processing photos/city.jpg
processing photos/old town.jpg
$ for f in photos/*.png; do echo "processing $f"; done
processing photos/*.png
$ shopt -s nullglob
$ for f in photos/*.png; do echo "processing $f"; done
$ shopt -u nullglob

Ranges of numbers

Brace expansion generates sequences of numbers or letters.

for i in {1..5}; do echo -n "$i "; done; echo
for i in {01..10..3}; do echo -n "$i "; done; echo
for c in {a..e}; do echo -n "$c "; done; echo
n=5
for i in {1..$n}; do echo -n "$i "; done; echo
for i in $(seq 1 $n); do echo -n "$i "; done; echo

{01..10..3} counts in steps of 3 and keeps the leading zero. Brace expansion happens before variables are expanded, so {1..$n} does not work. For ranges with variables, use seq or the C-style loop from the next section.

$ for i in {1..5}; do echo -n "$i "; done; echo
1 2 3 4 5
$ for i in {01..10..3}; do echo -n "$i "; done; echo
01 04 07 10
$ for c in {a..e}; do echo -n "$c "; done; echo
a b c d e
$ n=5
$ for i in {1..$n}; do echo -n "$i "; done; echo
{1..5}
$ for i in $(seq 1 $n); do echo -n "$i "; done; echo
1 2 3 4 5

The C-style for loop

The arithmetic form of for has an initialization, a condition, and an update, as in C.

for (( i = 0; i < 5; i++ )); do
    echo "iteration $i"
done
for (( i = 10; i > 0; i -= 3 )); do echo -n "$i "; done; echo

Inside (( )), variables need no $. This form works with variable limits and any step without starting external programs.

$ for (( i = 0; i < 5; i++ )); do
>     echo "iteration $i"
> done
iteration 0
iteration 1
iteration 2
iteration 3
iteration 4
$ for (( i = 10; i > 0; i -= 3 )); do echo -n "$i "; done; echo
10 7 4 1

while and until

while repeats as long as its condition succeeds; until repeats as long as it fails.

count=1
while (( count <= 3 )); do
    echo "count is $count"
    (( count++ ))
done
n=1
until (( n > 100 )); do
    (( n *= 3 ))
done
echo "first power of 3 above 100: $n"

The condition is any command, as with if; see the Bash conditionals article. Make sure that the body changes something the condition depends on, or the loop never ends. while true is a deliberate endless loop, left with break.

$ count=1
$ while (( count <= 3 )); do
>     echo "count is $count"
>     (( count++ ))
> done
count is 1
count is 2
count is 3
$ n=1
$ until (( n > 100 )); do
>     (( n *= 3 ))
> done
$ echo "first power of 3 above 100: $n"
first power of 3 above 100: 243

Reading a file line by line

while read with input redirected from a file processes the file one line at a time.

while read -r server; do
    echo "checking $server"
done < servers.txt

read reads one line into the variable and returns a non-zero status at the end of the file, which ends the loop. The redirection after done applies to the whole loop.

$ while read -r server; do
>     echo "checking $server"
> done < servers.txt
checking web1
checking web2
checking db1

The last line without a newline

Files created by some editors and programs do not end with a newline. read then returns failure for the last line, even though it has read it.

cat -A notes.txt; echo
while read -r line; do echo "[$line]"; done < notes.txt
while IFS= read -r line || [[ -n $line ]]; do echo "[$line]"; done < notes.txt

cat -A marks line ends with $; the last line has none. The simple loop silently drops it. Adding || [[ -n $line ]] continues the loop once more when the final read returned data.

$ cat -A notes.txt; echo
first line$
second line$
last line without newline
$ while read -r line; do echo "[$line]"; done < notes.txt
[first line]
[second line]
$ while IFS= read -r line || [[ -n $line ]]; do echo "[$line]"; done < notes.txt
[first line]
[second line]
[last line without newline]

IFS= and read -r

Without options, read changes the line: it strips leading and trailing whitespace and treats backslashes as escape characters.

printf '  indented line\npath C:\\temp\\new\n' > raw.txt
while read line; do echo "[$line]"; done < raw.txt
while IFS= read -r line; do echo "[$line]"; done < raw.txt

IFS= (an empty field separator, set only for the read command) keeps the whitespace, and -r keeps backslashes. while IFS= read -r line is the standard way to read lines exactly as they are.

$ printf '  indented line\npath C:\\temp\\new\n' > raw.txt
$ while read line; do echo "[$line]"; done < raw.txt
[indented line]
[path C:tempnew]
$ while IFS= read -r line; do echo "[$line]"; done < raw.txt
[  indented line]
[path C:\temp\new]

Splitting lines into fields

With several variable names, read splits the line into fields on the characters in IFS; the last variable gets the rest of the line.

while IFS=: read -r user _ uid _ _ home shell; do
    (( uid >= 1000 && uid < 60000 )) && echo "$user ($uid) $home $shell"
done < /etc/passwd
tail -n +2 users.csv | while IFS=, read -r name city age; do
    echo "$name, $age, lives in $city"
done

/etc/passwd has seven colon-separated fields; the conventional variable name _ takes the fields we do not need. UIDs from 1000 belong to regular users. The CSV file is read without its header line. This works for simple CSV only; quoted fields with commas need a real CSV parser.

$ while IFS=: read -r user _ uid _ _ home shell; do
>     (( uid >= 1000 && uid < 60000 )) && echo "$user ($uid) $home $shell"
> done < /etc/passwd
jano (1000) /home/jano /bin/bash
alice (1001) /home/alice /bin/sh
$ tail -n +2 users.csv | while IFS=, read -r name city age; do
>     echo "$name, $age, lives in $city"
> done
Peter, 34, lives in Bratislava
Lucia, 28, lives in Košice
Martin, 41, lives in Žilina

Pipes and lost variables

Each part of a pipeline runs in a subshell. Variables changed in a loop at the end of a pipe are lost when the loop ends.

total=0
cat servers.txt | while read -r server; do
    (( total++ ))
done
echo "servers: $total"
total=0
while read -r server; do
    (( total++ ))
done < servers.txt
echo "servers: $total"
total=0
while read -r server; do
    (( total++ ))
done < <(grep web servers.txt)
echo "web servers: $total"

The counter of the piped loop was incremented in a subshell, and the shell still sees 0. Redirecting the file into the loop keeps it in the current shell. When the input comes from a command, process substitution < <(command) does the same. (Alternatively, shopt -s lastpipe runs the last part of a pipeline in the current shell in scripts.)

$ total=0
$ cat servers.txt | while read -r server; do
>     (( total++ ))
> done
$ echo "servers: $total"
servers: 0
$ total=0
$ while read -r server; do
>     (( total++ ))
> done < servers.txt
$ echo "servers: $total"
servers: 3
$ total=0
$ while read -r server; do
>     (( total++ ))
> done < <(grep web servers.txt)
$ echo "web servers: $total"
web servers: 2

Do not loop over ls output

Looping over the output of a command with for x in $(...) splits it at every space, tab, and newline.

ls photos
for f in $(ls photos); do echo "[$f]"; done
for f in photos/*; do echo "[$f]"; done
find photos -name '*.jpg' -print0 | while IFS= read -r -d '' f; do
    echo "[$f]"
done

old town.jpg became two items. A glob gives correct file names directly. For recursive searches, find -print0 separates names with null bytes, which cannot occur in file names, and read -d '' reads up to each null byte. This handles any file name, including names with newlines. See the find article.

$ ls photos
beach.jpg
city.jpg
notes.txt
old town.jpg
$ for f in $(ls photos); do echo "[$f]"; done
[beach.jpg]
[city.jpg]
[notes.txt]
[old]
[town.jpg]
$ for f in photos/*; do echo "[$f]"; done
[photos/beach.jpg]
[photos/city.jpg]
[photos/notes.txt]
[photos/old town.jpg]
$ find photos -name '*.jpg' -print0 | while IFS= read -r -d '' f; do
>     echo "[$f]"
> done
[photos/old town.jpg]
[photos/beach.jpg]
[photos/city.jpg]

Lines into an array

For the same reason, for line in $(cat file) loops over words, not lines. mapfile reads lines into an array.

for line in $(cat notes.txt); do echo "[$line]"; done
mapfile -t lines < notes.txt
echo "${#lines[@]} lines"
for line in "${lines[@]}"; do echo "[$line]"; done

mapfile (also called readarray) stores each line in one element; -t removes the newlines. It also keeps the last line without a newline. ${#lines[@]} is the number of elements.

$ for line in $(cat notes.txt); do echo "[$line]"; done
[first]
[line]
[second]
[line]
[last]
[line]
[without]
[newline]
$ mapfile -t lines < notes.txt
$ echo "${#lines[@]} lines"
3 lines
$ for line in "${lines[@]}"; do echo "[$line]"; done
[first line]
[second line]
[last line without newline]

break and continue

continue skips to the next iteration, and break leaves the loop.

for n in 4 9 15 21 30; do
    if (( n % 2 == 0 )); then
        continue
    fi
    if (( n > 20 )); then
        echo "stopping at $n"
        break
    fi
    echo "odd: $n"
done
for x in 1 2 3; do
    for y in a b c; do
        [[ $x == 2 && $y == b ]] && break 2
        echo "$x$y"
    done
done

Even numbers are skipped, and the loop stops at the first odd number above 20. In nested loops, break 2 leaves both loops at once; continue 2 continues with the next iteration of the outer loop.

$ for n in 4 9 15 21 30; do
>     if (( n % 2 == 0 )); then
>         continue
>     fi
>     if (( n > 20 )); then
>         echo "stopping at $n"
>         break
>     fi
>     echo "odd: $n"
> done
odd: 9
odd: 15
stopping at 21
$ for x in 1 2 3; do
>     for y in a b c; do
>         [[ $x == 2 && $y == b ]] && break 2
>         echo "$x$y"
>     done
> done
1a
1b
1c
2a

A retry loop

Loops are often used to retry an operation that may fail temporarily, such as waiting for a service or a file.

retry.sh
#!/bin/bash

# tries a command up to five times, waiting longer after each failure
attempt=1
max=5

until [ -e ready.flag ]; do
    if (( attempt == max )); then
        echo "giving up after $attempt attempts" >&2
        exit 1
    fi
    echo "attempt $attempt failed, retrying in $attempt s"
    sleep "$attempt"
    (( attempt++ ))
    (( attempt == 3 )) && touch ready.flag   # simulate success
done

echo "ready after $attempt attempts"

The script checks a condition, waits longer after each failure, and gives up after a maximum number of attempts with a non-zero exit status. To make the example finish, it creates the flag file itself on the third attempt.

$ bash retry.sh
attempt 1 failed, retrying in 1 s
attempt 2 failed, retrying in 2 s
ready after 3 attempts

Looping over arrays

Arrays are the safe way to hold lists of items that may contain spaces.

fruits=(apple "passion fruit" cherry)
for fruit in "${fruits[@]}"; do
    echo "fruit: $fruit"
done
for fruit in ${fruits[@]}; do echo "fruit: $fruit"; done
for i in "${!fruits[@]}"; do echo "$i: ${fruits[i]}"; done
declare -A capitals=([Slovakia]=Bratislava [Austria]=Vienna [Hungary]=Budapest)
for country in "${!capitals[@]}"; do
    echo "$country -> ${capitals[$country]}"
done | sort

"${fruits[@]}", quoted, gives each element as one word. Without quotes, passion fruit is split. ${!fruits[@]} lists the indices. Associative arrays, declared with declare -A, map keys to values; their order is not defined, so the output is sorted.

$ fruits=(apple "passion fruit" cherry)
$ for fruit in "${fruits[@]}"; do
>     echo "fruit: $fruit"
> done
fruit: apple
fruit: passion fruit
fruit: cherry
$ for fruit in ${fruits[@]}; do echo "fruit: $fruit"; done
fruit: apple
fruit: passion
fruit: fruit
fruit: cherry
$ for i in "${!fruits[@]}"; do echo "$i: ${fruits[i]}"; done
0: apple
1: passion fruit
2: cherry
$ declare -A capitals=([Slovakia]=Bratislava [Austria]=Vienna [Hungary]=Budapest)
$ for country in "${!capitals[@]}"; do
>     echo "$country -> ${capitals[$country]}"
> done | sort
Austria -> Vienna
Hungary -> Budapest
Slovakia -> Bratislava

Commands that read standard input

Inside a while read loop, every command inherits the loop's input. A command that reads standard input, such as ssh, ffmpeg, or here cat, eats the rest of the file.

while read -r server; do
    echo "checking $server"
    cat > /dev/null
done < servers.txt
while read -r server; do
    echo "checking $server"
    cat > /dev/null < /dev/null
done < servers.txt

The first loop processed only web1, because cat read the remaining lines. Giving the inner command its own input, < /dev/null, fixes it; ssh has the -n option for the same purpose.

$ while read -r server; do
>     echo "checking $server"
>     cat > /dev/null
> done < servers.txt
checking web1
$ while read -r server; do
>     echo "checking $server"
>     cat > /dev/null < /dev/null
> done < servers.txt
checking web1
checking web2
checking db1

Asking questions inside a loop

The same problem appears when a loop over a file asks the user something.

ask.sh
#!/bin/bash

# the read inside the loop consumes the loop's input
while read -r server; do
    read -r -p "restart $server? " answer
    echo "answer for $server: $answer"
done < servers.txt

The inner read takes its answer from the file, so web2 becomes the answer for web1. The fixed version reads the file through file descriptor 3, leaving standard input to the terminal; the answers were typed in.

ask-fixed.sh
#!/bin/bash

# the loop reads from descriptor 3, so the inner read gets the terminal
while read -r server <&3; do
    read -r -p "restart $server? " answer
    echo "answer for $server: $answer"
done 3< servers.txt

3< servers.txt opens the file as descriptor 3 for the loop, and read <&3 reads from it.

$ bash ask.sh
answer for web1: web2
answer for db1:
$ bash ask-fixed.sh
restart web1? y
answer for web1: y
restart web2? n
answer for web2: n
restart db1? y
answer for db1: y

Menus with select

select prints a numbered menu, reads the user's choice, and repeats until break.

menu.sh
#!/bin/bash

PS3="Choose an action: "
select action in status restart quit; do
    case $action in
        status)  echo "showing status" ;;
        restart) echo "restarting" ;;
        quit)    echo "bye"; break ;;
        *)       echo "invalid choice: $REPLY" ;;
    esac
done

The prompt is taken from PS3. The variable gets the chosen item, or an empty value for an invalid number; REPLY holds what the user typed.

$ bash menu.sh
1) status
2) restart
3) quit
Choose an action: 2
restarting
Choose an action: 5
invalid choice: 5
Choose an action: 3
bye

Running iterations in parallel

A loop body put in the background with & runs concurrently with the other iterations; wait waits for all of them.

parallel.sh
#!/bin/bash

# runs the jobs in the background and waits for all of them
for job in 1 2 3 4; do
    (
        sleep 2
        echo "job $job done"
    ) &
done

wait
echo "all jobs finished"

The four jobs of two seconds each finished in two seconds in total. The order of their output is not guaranteed. To limit the number of concurrent jobs, xargs -P is usually simpler; see the xargs article.

$ time bash parallel.sh
job 1 done
job 2 done
job 3 done
job 4 done
all jobs finished

real	0m2.007s
user	0m0.003s
sys	0m0.013s

Useful one-liners

Short loops are handy on the command line.

for f in photos/*.jpg; do mv -- "$f" "${f%.jpg}.jpeg"; done; ls photos
for d in /etc/apt /etc/ssh /nonexistent; do [ -d "$d" ] && echo "$d: $(ls "$d" | wc -l) entries"; done
for i in {1..3}; do echo "line $i"; done > out.txt; cat out.txt

The first loop renames files, using ${f%.jpg} to remove the extension; -- protects against names that start with a dash. The second counts entries in existing directories. The third shows that the output of a whole loop can be redirected at done.

$ for f in photos/*.jpg; do mv -- "$f" "${f%.jpg}.jpeg"; done; ls photos
beach.jpeg
city.jpeg
notes.txt
old town.jpeg
$ for d in /etc/apt /etc/ssh /nonexistent; do [ -d "$d" ] && echo "$d: $(ls "$d" | wc -l) entries"; done
/etc/apt: 6 entries
/etc/ssh: 11 entries
$ for i in {1..3}; do echo "line $i"; done > out.txt; cat out.txt
line 1
line 2
line 3

Best practices

Source

Bash manual: Looping Constructs, BashFAQ/001: How can I read a file line by line?

In this article, we have written for, while, until, and select loops, read files line by line and field by field, avoided word-splitting, subshell, and stdin pitfalls, used break and continue, and run iterations in parallel. See also the Bash conditionals, shell expansion, and Bash quoting articles.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Linux tutorials.