Monday, 27 June 2011

Conditional Structures in Shell Scripting - III


After if..else  and if..elfi..else we move to looping structures. Looping is supported in the form of for and while. Again they work semantically the same but syntactically different.

for Loop
Syntax
In bash shell there are two syntaxes.

1. for variable in list
   do 
     statement1 is executed till the list exhausts
   done

2. traditional for
 for (( variable_init ; condition ; variable_increment/decrement ))
   do
              statement1 is executed 
      till the condition returns false 
      done


Example:

for i in 1 2 3 4 5
do
echo "Testing $i times"
done
view raw fortest.sh hosted with ❤ by GitHub

Same program with second syntax

#Here the spaces are for formatting purposes only.for is not sensitive to spaces
for (( i=0 ; i<=5 ; i++ ))
do
echo "Testing $i times"
done
view raw fortest2.sh hosted with ❤ by GitHub

while Loop
Nothing new about it. Just loops through the series of statements until the condition is true.
Syntax:
          #sensitive to white spaces
          while [ condition ]
          do
              statement1
              statement2
           done


echo "Enter the number"
read x
#initialize looping variable
i=0
#check if i is less than 10
while [ $i -le 10 ]
do
#print the value of x * i
echo " $x * $i = $(( $x * $i ))"
#increment i by 1
i=$(( $i + 1 ))
done
view raw whiletest.sh hosted with ❤ by GitHub

case Statement
case in bash scripting is very similar to switch case semantically . It save the trouble for writing a multilevel elif statements.

Syntax:

case $variable in
case1)  statement1;;
case2)  statement2;;
..
..
caseN) statementN;;
esac
echo "Enter the number"
read x
case $x in
1) echo "You entered one";;
2) echo "You entered two";;
3) echo "You entered three";;
4) echo "You entered four";;
5) echo "You entered five";;
*) echo "Sorry not listed";;
esac
view raw case.sh hosted with ❤ by GitHub











No comments:

Post a Comment

Popular Posts