Loops
There are three statements built into the language that allow you to run commands in a loop. All redirections applied on each loop statment is applied on all commands within the loop.
Whenever a semicolon ; appears in the examples below, it may be replaced with one or more newlines.
until
The syntax of the until loop is:
until test-commands; do consequent-commands; doneThe until loop executes consequent-commands as long as test-commands has an exit status which is not zero. The return status is the exit status of the last command executed in consequent-commands.
For example:
until false; do
echo foobar
donewhile
The syntax of the while loop is:
while test-commands; do consequent-commands; doneThe while is the opposite of until loop. it executes consequent-commands as long as test-commands has an exit status of zero. The return status is the exit status of the last command executed in consequent-commands.
For example:
while true; do
echo foobar
donefor
The for loop can be constructed in 3 different formats.
Loop over positionals
The format is as follows:
for NAME do consequent-commands; doneThis format will execute consequent-commands once for each positional argument that is set. the NAME is a variable name that will hold the value of the positional argument under examination.
For example:
for arg do
echo $arg
doneIf the positional arguments are foo bar baz, the output would be:
foo
bar
bazLoop over arguments
The format looks similar to above:
for NAME in arguments; do
consequent-commands
doneThis format will execute consequent-commands once for each field of the list resulted from the expansion of arguments.
For example:
for user in bob yassine phank; do
echo $user
donethe output would be:
bob
yassine
phankC-like for loop
The third format is similar to the for loop in C programming language.
for (( expr1; expr2; expr3 )) do
commands
doneexpr1, expr2 and expr3 are Arithmetic Expressions.
First, the arithmetic expression expr1 is evaluated. The arithmetic expression expr2 is then evaluated repeatedly until it evaluates to zero. Each time expr2 evaluates to a non-zero value, commands are executed and the arithmetic expression expr3 is evaluated. If any expression is omitted, it behaves as if it evaluates to 1. The return value is the exit status of the last command in commands that is executed.
For example:
for (( i = 0; i < 3; i++ )) do
echo $i
doneThis would output:
0
1
2