Shell Scripting Lesson 8 - Loops

Looping in shell Scripts are there to you. You Can use four types of loops.

1. while-do loops
2. for loops
3. until loops
4. select loops.

I will give you examples for all four types of loops.


While-do loops.

while command
do
statements to be looped
done

See the below Example to get more understand about while loops.
#!bin/sh

num=1
while [ $a -lt 10 ]
do
echo "Tutorial No : ".$num 
num =`expr $num  + 1`
done


For loops

for var in val1 val2 val3...... valN
do
statements to be looped
done

See the below example.
for var in  1 2 3 4 5 6 7 8 9 10
do
echo "Tutorial No: ".$var
done

Until loops.
 if you want to loop something until your condition true, until loops are the best solution for your requirement.

until command
do
statements to be looped
done

See the below example.
#!/bin/sh
num=0
until [ ! $num -lt 10 ]
do
   echo "Tutorial No: ".$num
   num=`expr $num + 1`
done
 
Select Loops.
select loops are used in creating menus.

select var in val1 val2 val2 .....valN
do
statements to be looped
done


See the below Example..
select Tutorial in shell awk php js none
do
case $tutorial in
awk|shell
echo "Linux Tutorials"
;;
php)
echo "server side scripting tutorial"
;;
js)
echo "client side scripting Tutorial"
;;
none)
break
;; 
*)
echo "Invalid Selection"
;;
esac
done

This the End of today Lesson !

0 comments:

Post a Comment

Ask anything about this Tutorial.