Loops are programming structures that repeat a block of program statements until a given condition is met.
There are three types of shell loops in UNIX/Linux:
The for loop operates on a list of items. The statements in the for loop are executed for all items in the list. The for loop is initialized as follows:
for var in word1 word2 ... wordN
do
Statement(s) to be executed
done
The code below demonstrates the use of the for loop.
for a in 10 8 6 4 2doecho $a # print adone
In first iteration of the loop, var
will be assigned the var
= 8. In the third iteration, var
= 6, and so on.
The statements in the while loop are executed until the command in the condition becomes false. The while loop is initialized as follows:
while command
do
Statement(s) to be executed
done
The code below demonstrates the use of the while loop.
a=10while [ $a -gt 0 ] # a > 0doecho $a # print aa=`expr $a - 2` # a = a - 1done
The statements in the until loop are not executed until the command in the condition becomes true. The until loop is initialized as follows:
until command
do
Statement(s) to be executed
done
The code below demonstrates the use of the until loop.
a=10until [ $a -lt 2 ] # a < 2doecho $a # print aa=`expr $a - 2` # a = a - 1done
A variable (a
) is initialized with a = 10
in line 1. The until loop in line 3 executes until the condition (a < 2
) is false. When a < 2
becomes true, the loop breaks.
Free Resources