Monday, April 13, 2009

For and while loop in shell script

In any programming language there is looping structure. Looping is used to do a repeating task with one instruction.
Bash shell supports for and while loop.

The basic structure of for and while loop is,

1)Variable initialization.
2)Checking condition.
3)Execute instruction and increment the initialization variable.

For loop in shell script
The syntax for for loop is,

for { variable name } in { list }
do
execute statement upto done
done

For each item in the list execute statements between do and done.

A very simple example using above syntax is given below.

# cat for_loop1.sh
for i in 1 2 3 4 5
do
echo "*$i*"
done

# chmod +x for_loop1.sh

# ./for_loop1.sh
*1*
*2*
*3*
*4*
*5*

A variation of the above for loop syntax is,

for (( expr1; expr2; expr3 ))
do
execute statements between do and done until expr2 becomes false.
done

An example of this syntax is given below.

# cat for_loop2.sh

echo -n "Enter the number of times loop will iterate: "
read number
for (( i=0 ; i < $number ; i++ ))
do
for (( j=0 ; j <= i ; j++ ))
do
echo -n "*"
done
echo ""
done

# chmod +x for_loop2.sh

# ./for_loop2.sh
Enter the number of times loop will iterate: 7
*
**
***
****
*****
******
*******

While loop in shell script
The syntax of the while loop is,

while [ condition ]
do
execute commands
done

The latest example that is shown in case of for loop can be converted in case of while loop as below.

# cat while_loop.sh
i=0
echo -n "Enter the number of times to iterate the loop: "
read number
while [ $i -lt $number ]
do
j=0
while [[ $j -le $i ]]
do
echo -n "*"
j=`expr $j + 1`
done
echo ""
i=`expr $i + 1`
done

# chmod +x while_loop.sh

# ./while_loop.sh
Enter the number of times to iterate the loop: 6
*
**
***
****
*****
******

Related Documents
http://arjudba.blogspot.com/2009/04/checking-condition-in-shell-scipt-by.html

No comments:

Post a Comment