Unix
In this tutorial we will learn about While loop in Shell Programming.
The while
loop is similar to a for loop and help in executing a block of code multiple times as long as some given condition is satisfied.
while [ condition ]
do
# body of while loop
done
Where condition
is some condition which if satisfied results in the execution of the body of the loop.
To come out of the while loop we make the condition fail.
To quit the script we can use the exit
command.
#!/bin/sh
# initialise i
i=1
while [ $i -le 5 ]
do
# echo i
echo $i
# update i
i=`expr $i + 1`
done
Output:
$ sh example01.sh
1
2
3
4
5
We can achieve the same result by write the following code.
#!/bin/sh
# initialise i
i=1
while [ $i -le 5 ]
do
# echo i
echo $i
# update i
i=$(( $i + 1 ))
done
We can nest while loop by placing a while loop in the body of another while loop.
while [ condition_outer ]
do
# body of the outer while loop
while [ condition_inner ]
do
# body of the inner while loop
done
done
1
1 3
1 3 5
1 3 5 7
For this we will use r
variable to count the rows and c
variable to count the columns. And we will use counter
variable to print the number.
#!/bin/sh
# for the rows
r=1
while [ $r -le 4 ]
do
# for the output
count=1
# for the column
c=1
while [ $c -le $r ]
do
# print the value
printf "$count "
# update count
count=$(( $count + 2 ))
# update c
c=$(( $c + 1 ))
done
# go to new line
printf "\n"
# update r
r=$(( $r + 1 ))
done
Output:
$ sh example02.sh
1
1 3
1 3 5
1 3 5 7
ADVERTISEMENT