Loops - for, while and until

Beginner · 10 min

Repeat work over files, lists, counters and lines of input with for, while and until, and avoid the classic traps of looping over ls output.

Before thisGlobbing and wildcardsConditionals with if, test and double bracketsBrace and tilde expansion

Microsoft Developer · 10 min

Loops - for, while and until

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Microsoft DeveloperReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `for name in list; do ...; done` runs the body once per word. The list can be literal words, a glob, a brace range or `"$@"`.
  • Loop over files with a glob, never over `$(ls)`. Command output is split on whitespace, so a name with a space becomes two items.
  • `while` repeats as long as a command succeeds and `until` repeats until it does. `while IFS= read -r line; do ...; done < file` is the standard way to process a file line by line.
  • `break` leaves a loop and `continue` skips to the next pass. The C-style `for ((i = 0; i < n; i++))` is the right tool when the bound is a variable.
  • A pipeline's loop body runs in a subshell, so variables set inside are lost. Redirect from a file or a process substitution when you need the result.

Doing something to many things

You have three weekly log files and want a summary of each. You could run the command three times. If it were 300 files, that would stop being an option. A loop repeats a block of commands, and Bash has three kinds: for walks a list, while repeats as long as a command succeeds, and until repeats until one does.

Here is logsum version 3. It takes any number of files and prints one line for each. ShellCheck found nothing in it.

#!/usr/bin/env bash
# logsum v3: one line per log file
for log in "$@"; do
  total=$(wc -l < "$log")
  errors=$(awk '$8 >= 500' "$log" | wc -l)
  printf '%-20s requests=%d errors=%d\n' "${log##*/}" "$((total))" "$((errors))"
done

I split the 200-line fixture into three files, one deliberately named wed night.log with a space in it:

$ ./logsum logs/*.log
mon.log              requests=70 errors=8
tue.log              requests=70 errors=9
wed night.log        requests=60 errors=7

Eight plus nine plus seven is 24, the same server-error total as the whole file. "$@" kept the file with a space intact, and so did the glob.

for over a list

The list after in is just words, and everything you know about expansion applies to it: literal words, globs, {1..3} braces, or variables.

$ for color in red green blue; do echo "color: $color"; done
color: red
color: green
color: blue
$ for i in {1..3}; do echo "pass $i"; done
pass 1
pass 2
pass 3

If you want a counter bounded by a variable, the braces won’t work (they expand before variables), and the C-style form does:

$ for ((i = 0; i < 3; i++)); do echo "c-style $i"; done
c-style 0
c-style 1
c-style 2

Don’t loop over ls

It is tempting to write for log in $(ls logs). It is also a bug. The output of ls is split on whitespace, because it is an unquoted command substitution, so a space in a filename splits the name in two:

$ bash bad.sh
found: mon.log
found: tue.log
found: wed
found: night.log

One file became two bogus items. Use a glob (logs/*), which keeps each name as a single word. ShellCheck reports the ls version as SC2045, “Iterating over ls output is fragile. Use globs.”

A glob with no matches is the other hazard. Bash leaves the pattern as typed, so the loop runs once with a name that doesn’t exist:

$ for f in logs/nothing*.log; do echo "ran with: $f"; done
ran with: logs/nothing*.log
$ shopt -s nullglob; for f in logs/nothing*.log; do echo "ran with: $f"; done; echo "nullglob: loop skipped"
nullglob: loop skipped

With nullglob set, an unmatched pattern expands to nothing, so the loop body never runs. Check for the file inside the loop ([[ -e $f ]] || continue) if you can’t rely on the option.

while and until

while and until take a command as the condition, just like if. They are for repeating until something changes.

$ n=0; while [ "$n" -lt 3 ]; do n=$((n + 1)); echo "while $n"; done
while 1
while 2
while 3
$ tries=0; until [ "$tries" -ge 3 ]; do tries=$((tries + 1)); echo "until $tries"; done
until 1
until 2
until 3

The most common use of while is to read input line by line:

$ while IFS= read -r name; do echo "hello, $name"; done < names.txt
hello, ada
hello, linus
hello, grace

Two details protect the data. IFS= stops read from trimming leading and trailing whitespace, and -r stops it treating backslashes as escapes. Leave both off only when you want that behaviour. The reading input lesson goes deeper.

break leaves the loop, and continue skips to the next item:

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

The pipeline trap

A loop at the end of a pipeline runs in a subshell, a child copy of the shell. Anything it sets disappears when it ends:

$ count=0; printf 'a\nb\nc\n' | while read -r line; do count=$((count + 1)); done; echo "count after pipe loop: $count"
count after pipe loop: 0
$ count=0; while read -r line; do count=$((count + 1)); done < <(printf 'a\nb\nc\n'); echo "count after process substitution: $count"
count after process substitution: 3

Same loop, same input. The second form sends the output in through a process substitution, so the loop runs in your shell. The subshell lesson explains why.

About the video

“What are Loops in Bash? [18 of 20] | Bash for Beginners” is part of Microsoft Developer’s Bash for Beginners series, presented by Gwyn. It is 10 minutes 12 seconds and was published in February 2023. I could not read a transcript, but the description has chapters that match this lesson: the while loop at 0:47, the until loop at 2:30, for loops at 4:04 and break at 8:05. It is in English. It doesn’t cover continue, globbing hazards, read loops or the pipeline subshell trap, which come from my own runs above. Nick Janetakis’s while-and-until examples and Learn Linux TV’s for-loop video are linked as second views.

Where this fits

Loops repeat a block. When you have one value and many things it might equal, case is cleaner than a ladder of ifs.

Check yourself

  1. 01Why is `for f in $(ls)` unsafe, and what replaces it?

    The output of `ls` is split on whitespace, so `wed night.log` becomes two items. Use a glob, such as `for f in logs/*.log`, which yields each name intact.

  2. 02What happens when `for f in logs/nothing*.log` matches no files?

    Bash leaves the pattern as written, so the body runs once with `f` set to the literal `logs/nothing*.log`. `shopt -s nullglob` makes an unmatched glob expand to nothing.

  3. 03How do you read a file line by line without trimming spaces or mangling backslashes?

    `while IFS= read -r line; do ...; done < file`. `IFS=` stops leading and trailing whitespace trimming, and `-r` stops backslash processing.

  4. 04You count lines in `printf ... | while read ...` and the counter is 0 afterwards. Why?

    Each stage of a pipeline runs in its own subshell, so the loop increments a copy of the variable. Feed the loop with `< <(command)` or a file instead.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark