The Loop is one of the important control statement in Unix that enables you to execute set of commands repeatedly. The following type of loops are mostly used in Unix Shell.
- For loop
- While loop
- Until loop
For loop:
For loop repeats through a set of values until the list is tired.
Ex:
1 2 3 4 5 6 7 8 9 |
#!/bin/sh for i in 1 2 3 4 5 do echo "Welcome $i times" done |
Output:
1 2 3 4 5 6 7 8 9 |
Welcome 1 times Welcome 2 times Welcome 3 times Welcome 4 times Welcome 5 times |
To find the smallest among the given numbers using for loop,
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#!/bin/bash smallest=10000 for i in 5 8 19 8 7 3 do if test $i -lt $smallest then smallest=$i fi done echo $smallest |
Output: 3
Note:
This program calculates the smallest among the numbers
1 |
5, 8, 19, 8, 3. |
While loop:
While loops repeat statements as long as the next Unix command is successful. It works similar to the while loop in C.
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#! /bin/sh i=1 sum=0 while [ $i -le 100 ] do sum=`expr $sum + $i` i=`expr $i + 1` done echo The sum is $sum. |
Output:
1 |
The sum is 5050 |
NOTE:
The value of i is tested in the while to see if it is less than or equal to 100.
Until loop:
Until loops repeat statements until the next Unix command is successful. It Works similar to the do-while loop in C.
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#! /bin/sh x=1 until [ $x -gt 3 ] do echo x = $x x=`expr $x + 1` done |
Note:
The value of x is tested in the until to see if it is greater than 3.