What is loop control in Unix/Linux?
Looping statements
The three keywords to loop in Unix/Linux shell are as follows:
1. until
The statements in the until loop are executed until the command in the condition becomes true.
Syntax
The following is the syntax of the until loop:
until command
do
Statement(s) to be executed
done
Code
The code below demonstrates the use of the until loop.
a=5until [ $a -lt 1 ] # a < 1doecho $a # print aa=`expr $a - 1` # a = a - 1done
2. while
The statements in the while loop are executed until the command in the condition becomes false.
Syntax
The following is the syntax of the while loop:
while command
do
Statement(s) to be executed
done
Code
The code below demonstrates the use of the while loop.
a=5while [ $a -gt 0 ] # a > 0doecho $a # print aa=`expr $a - 1` # a = a - 1done
3. for
The for loop operates on a list of items. The statements in the for loop are executed for all items in the list.
Syntax
The following is the syntax of the for loop:
for var in word1 word2 ... wordN
do
Statement(s) to be executed
done
Code
The code below demonstrates the use of the for loop.
for a in 5 4 3 2 1doecho $a # print adone
Altering loops
We use the following keywords to alter the normal flow of a loop in Unix/Linux:
1. break
We use the break statement to terminate the loop. It executes the line above break and ignores all the lines below break. It then starts execution from the next line after the end of the loop.
Code
The code below demonstrates the use of the break statement.
for a in 2 5 3 1 9 8 0 7 6 4doif [ $a -eq 0 ] # a == 0thenbreakfiecho $adone
2. continue
We use the continue statement to terminate iteration(s) of the loop. It executes the line above continue and ignores all the lines below continue. It then starts execution from the start of the next iteration in the loop.
Code
The code below demonstrates the use of the continue statement.
for a in 1 2 3 4 5 6 7 8 9 10doif [ `expr $a % 2` -eq 0 ] # a % 2 == 0thencontinuefiecho $adone
Free Resources