Loops
Loops allow you to execute the same code on different values of a variable
Below, we give the syntax and examples for for
and while
loops.
for
loops
General syntax:
1 2 3 4 |
|
Here, var
is a variable name, and list
is a list of items separated by
white space that var
will take on in the loop iterations.
Example:
test.sh | |
---|---|
1 2 3 4 5 |
|
This is the result of a sample run.
input | |
---|---|
1 |
|
output | |
---|---|
1 2 3 4 5 |
|
The looping expression can also use a format similar to a C for loop. For example, this script also gives a same results.
1 2 3 4 5 |
|
while
loops
General syntax:
1 2 3 4 |
|
Here, expression
is a conditional expression as described in Conditional statements.
Example:
test.sh | |
---|---|
1 2 3 4 5 6 7 8 |
|
This is the result of a sample run.
input | |
---|---|
1 |
|
output | |
---|---|
1 2 3 4 5 6 7 8 9 |
|