Unix Tutorial 12 : Loop Types

Loops in Unix

You may use different loops based on the situation.
They are:
#1) Unix For loop statement
Example: This program will add 1+2+3+4+5 and result will be 15
for i in 1 2 3 4 5
 do
 sum=`expr $sum + $i`
 done
 echo $sum
#2) Unix While loop statement
Example: This program will print the value of ‘a’ five times, from 1 to 5.
a=1
 while [ $a -le 5 ]
 do
 echo “value of a=” $a
 a=`expr $a + 1`
 done
#3) Unix Until loop statement
This program will print the value of ‘a’ two times from 1 to 2.
a=1
 until [ $a -ge 3 ]
 do
 echo “value of a=” $a
 a=`expr $a + 1`
 done
While running these loops, there may be a need to break out of the loop in some condition before completing all the iterations or to restart the loop before completing the remaining statements. This can be achieved with the ‘break’ and ‘continue’ statements.
The following program illustrates the ‘break’ operation:
 num=1
 while [ $num -le 5 ]
 do
 read var
 if [ $var -lt 0 ]
 then
 break
 fi
 num=`expr $num + 1`
 done
 echo “The loop breaks for negative numbers”

Comments

Popular posts from this blog

Hive Tutorial 31 : Analytic Functions

Hive Tutorial 37 : Performance Tuning