Loops#
There are several looping constructs in bash. The most straight forward constructs are loop-while and loop-until. The for-loop is very powerful in combination with shell globbing.
Loop-while and Loop-until#
Very much like conditionals the while and until statements evaluate the exit code of test command. The difference is, until
loops as long as this exit code is non-zero and while
loops as long as it is equal to zero.
until test-cmd ; do
... # repeat this as long as test-cmd has a non-zero exit code
done
while test-cmd ; do
... # repeat this as long as test-cmd has exit code zero
done
These loops are (compound) commands themselves. In particular they have exit codes and rules for redirection apply. A very common pattern is to loop over lines in a file:
while IFS="" read -r line ; do
# to something with "$line"
done < data.txt
The bash built-in read -r
reads words from stdin
until a newline character occurs and stores them in given variables (here just line
). The word boundaries are defined by the environment variable IFS
(internal field separator). Setting this to on empty string (just for that read
command) defines the whole line as one “word”. Finally via input redirection stdin
is replaced with the file data.txt
.
Similar, if data.csv
contains lines with key/value pairs (e.g. key1;value1
), these fields could be read in directly:
while IFS=";" read -r key value ; do
# to something with "$key" and "$value"
done < data.txt