Loops
For loop
for <varname>; do
commands;
done
- Iterates through a loop once for each command-line argument.
- Stores the value of the current argument in the specified variable.
for arg; do
echo "Argument: $arg"
done
For-in loop
for <varname> in <list of values>; do
commands;
done
- Iterates through a loop once for each value in the specified list.
- Stores the value of the current list item in the specified variable.
for item in apple orange; do
echo "List item: $item"
done
for value in $@; do
echo "List item: $value"
done
for img in *.png; do echo $img; done
for img in *.png; do
echo $img;
done
While loop
while <command>; do
commands;
done
- Iterates through a loop as long as the specified command is true.
index="3"
while [ "$index" -gt "0" ]; do
echo Index: $index
let index=index-1
done
Until loop
until <command>; do
commands;
done
- Iterates through a loop as long as the specified command is not true.
index="3"
until [ "$index" -eq "0" ]; do
echo "Index: $index"
let "index = index - 1"
done
Jump statements
- break [n] : Break from the innermost n loops (the default is 1).
- continue [n] : Continue on to the next iteration of the innermost n loops (the default is 1).
Resources URL:
notes/bash/resources
Sources URL:
notes/bash/sources