Loops
From the source: GNU bash manual: Loops.
Iterating over a list of arguments
Apply command to each element in a list:
for x in a b c; do command $x done
If unquoted, the list of elements is subjected to all the usual shell preprocessing (filename expansion etc.), see quoting arguments.
Iterating over nothing
If the list of elements is empty, the loop body is never executed:
for x in; do command $x # never executed done myarray=() for x in "${myarray[@]}"; do command $x # never executed done
Looping n times (using a for-loop)
This is a very low-level way to iterate. If possible, use a for x in...-loop, as described above.
The traditional (C) way to do this is, in bash:
for ((i=0 ; i<10; i++)); do echo $i; done
There are several more elegant solutions available, one of which is using the seq command:
for i in $(seq 0 1 9); do echo $i; done
This provides much greater flexibility defining the first, last and step values of the loop.
Looping while some condition is true
Keep executing a command while a condition is true:
while test "$(pwd)" != "/"; do cd .. echo $(pwd) done
Note that:
- If the condition is false the first time, the commands are never executed.
- If the condition never becomes false, the loop is infinite.
Looping until some condition is true
Keep executing a command as long as a condition is false:
until test "$(pwd)" == "/"; do cd .. echo $(pwd) done
Note that:
- If the condition is true the first time, the commands are never executed.
- If the condition never becomes true, the loop is infinite.
An until-loop is simply a while-loop with the condition negated. Hence, a while-loop might be more readable written using the equivalent until-loop:
while ! condition; do...
until condition; do...