Learn/Bash/5. Loops
Lesson 5 of 8
Sign in

Bash, lesson 5

Loops

Loops are where shell scripts save you real time: rename a hundred files, check every line of a log, retry a command until it works. Bash has for, while and until loops, and every one of them wraps its body in do ... done.

for over a list of words

The simplest for loop walks through a list of words:

To count, use brace expansion, which generates the list for you, or a C-style loop:

Brace expansion like {1..5} happens before variables are expanded, so {1..$n} does not work. When the end comes from a variable, use the C-style form: for (( i = 1; i <= n; i++ )).

while loops

A while loop runs as long as its test command succeeds:

2 exercises to try what you just read.

Exercise 1

Countdown

Press Ctrl Enter or Check to test your code.

Exercise 2

Step counter

Press Ctrl Enter or Check to test your code.

until is the mirror image: it loops as long as the test fails.

Reading every line of input

This pattern is one of the most useful in Bash. read succeeds while there is a line to read and fails at the end of input, so it makes a perfect while test:

There is a catch: if the very last line has no newline at the end, read stores it but still reports failure, so the loop skips it. The robust version also accepts a non-empty leftover:

break and continue

  • break leaves the loop immediately.
  • continue skips to the next round.

Keeping a running total

Variables set inside a loop keep their values after it, so the classic patterns work as you would expect:

(One exception to remember for later: if you pipe into a loop, as in some_command | while read -r x, the loop runs in a separate process and its variables vanish when it ends. Reading from the script's own input, as here, has no such problem.)

Further reading

  • Bash manual: Looping constructs
  • Bash manual: Brace expansion
  • Bash manual: The read builtin

Read a whole number n (0 or more) and count down from n to 1, one number per line, then print Liftoff!.

Sample input:

Sample output:

Each input line holds the number of steps walked on one day. Read lines until the input ends or until a line says stop (the last line may not end with a newline). Print the number of days counted, the total steps, and how many days reached the goal of 10000 steps or more.

Sample input:

Sample output:

for fruit in apple pear plum; do
    echo "I like $fruit"
done
for i in {1..5}; do echo "Lap $i"; done

for (( i = 10; i > 0; i -= 2 )); do
    echo "$i"
done
n=1
while (( n < 100 )); do
    (( n *= 2 ))
done
echo "$n"   # 128
while read -r line; do
    echo "Got: $line"
done
while read -r line || [[ -n $line ]]; do
    echo "Got: $line"
done
for n in {1..10}; do
    (( n % 2 == 0 )) && continue   # skip even numbers
    (( n > 7 )) && break           # stop after 7
    printf "%d " "$n"
done
echo                               # prints: 1 3 5 7
total=0
while read -r price; do
    (( total += price ))
done
echo "Total: $total"
3
3
2
1
Liftoff!
8200
12050
10000
stop
99999
Days: 3
Total: 30250
Goal days: 2