shellstreak

Bash for loop examples

Updated · Every command on this page ran in our practice shell

Short answer

A bash for loop is for item in list; do commands; done. Loop over files with for f in *.txt; do echo "$f"; done, over numbers with for n in {1..5}, and always quote "$f" so names with spaces stay whole. while [ test ]; do ...; done repeats while a test is true.

A loop runs the same commands for each item in a list: every file in a folder, every number from 1 to 10, every line of a file. The examples below ran in a practice shell on a folder of bakery orders, whose file names have spaces in them on purpose.

Loop over a list of words

The shape is for name in list; do commands; done. Inside the loop, $name holds the current item.

example
learner@shellstreak:~/bakery$ for bread in sourdough rye focaccia; do echo "Baking $bread"; done
Baking sourdough
Baking rye
Baking focaccia

Loop over files with a glob

A wildcard like orders/*.txt expands to the matching file names, sorted. This is the right way to loop over files; don't loop over the output of ls.

example
learner@shellstreak:~/bakery$ for f in orders/*.txt; do echo "$f: $(wc -l < "$f") lines"; done
orders/april 01.txt: 3 lines
orders/march 01.txt: 2 lines
orders/march 02.txt: 1 lines

Quote "$f" for names with spaces

Without quotes, bash splits a variable's value on spaces, so march 01.txt becomes two arguments, march and 01.txt. With rm or mv, that can hit the wrong file. Write "$f" every time.

example
learner@shellstreak:~/bakery$ f="march 01.txt"; for w in $f; do echo "[$w]"; done; for w in "$f"; do echo "[$w]"; done
[march]
[01.txt]
[march 01.txt]

Loop over a range of numbers

Brace expansion {1..5} produces the numbers 1 to 5. For ranges held in variables, use the C-style loop for ((i = 1; i <= n; i++)), or seq 1 "$n".

example
learner@shellstreak:~/bakery$ for n in {1..3}; do echo "Tray $n"; done
Tray 1
Tray 2
Tray 3

while loops and counters

while repeats as long as its test succeeds. $(( )) does arithmetic, so i=$((i + 1)) counts up.

example
learner@shellstreak:~/bakery$ i=1; while [ $i -le 3 ]; do echo "Batch $i"; i=$((i + 1)); done
Batch 1
Batch 2
Batch 3

Read a file line by line

while read -r reads one line per round from the file given after done. Name several variables to split each line on spaces. -r keeps backslashes as they are.

example
learner@shellstreak:~/bakery$ while read -r qty item; do echo "$item x$qty"; done < "orders/april 01.txt"
focaccia x1
rye x3
sourdough x2

Functions

name() { commands; } defines a function. Call it like a command; inside, $1, $2 and $@ are its own arguments. Functions keep the body of a loop short and readable.

example
learner@shellstreak:~/bakery$ greet() { echo "Hello, $1"; }; for p in Ana Ben; do greet "$p"; done
Hello, Ana
Hello, Ben

Preview a loop before it changes anything

Put echo in front of the command that deletes or moves files. The loop prints exactly what it would run; when the list looks right, take the echo out.

example
learner@shellstreak:~/bakery$ for f in orders/march*.txt; do echo rm "$f"; done
rm orders/march 01.txt
rm orders/march 02.txt

Check yourself

One real exercise from the “Shell scripting” unit. No account needed.

Print the name of every script in scripts (every scripts/*.sh), with a for loop.

What's checked: the output of your last command.

Common mistakes

  • Looping over $(ls). It splits names with spaces into pieces. Use a glob: for f in *.txt.

  • Leaving $f unquoted inside the loop, especially with rm, mv and cp.

  • Forgetting that a glob with no matches stays as the literal text, like *.zip. Check with [ -e "$f" ], or turn on shopt -s nullglob.

  • Missing do, done or the ; before them on a one-line loop.

  • Writing a loop that deletes or moves files in a script without set -euo pipefail at the top. Then a failed step doesn't stop the rest.

Questions

How do I write a for loop on one line?+

Separate the parts with semicolons: `for f in *.txt; do echo "$f"; done`.

How do I stop a loop early or skip an item?+

`break` leaves the loop completely; `continue` skips to the next item.

How do I loop over the lines of a file?+

Use `while read -r line; do ...; done < file`. A `for` loop over `$(cat file)` splits on every space, not just on new lines.

Reading is step one. Now make it stick.

Practise this in a five-minute lesson with instant feedback. No account needed.

Practise it now