Bash, lesson 5
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.
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++ )).
A while loop runs as long as its test command succeeds:
2 exercises to try what you just read.
until is the mirror image: it loops as long as the test fails.
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 leaves the loop immediately.continue skips to the next round.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.)
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"
donefor i in {1..5}; do echo "Lap $i"; done
for (( i = 10; i > 0; i -= 2 )); do
echo "$i"
donen=1
while (( n < 100 )); do
(( n *= 2 ))
done
echo "$n" # 128while read -r line; do
echo "Got: $line"
donewhile read -r line || [[ -n $line ]]; do
echo "Got: $line"
donefor 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 7total=0
while read -r price; do
(( total += price ))
done
echo "Total: $total"33
2
1
Liftoff!8200
12050
10000
stop
99999Days: 3
Total: 30250
Goal days: 2