Sunday, 26 June 2011

Conditional Structures in Shell Scripting - II


Nested if..else
Nested if else statements can be useful to check multiple conditions. For example, given a number first check whether it is positive or negative then  test the range in the respective domains.
Syntax:
                       if condition
           then
               if condition
               then
                  statement1
               else
                  statement2
               fi
                  else
               statement3
               fi

Example :
read x
if [ $x -ge 0 ]
then
if [ $x -ge 10 -a $x -le 100 ]
then
echo "$x is between 10 and 100"
else
echo "$x is between 0 and 9"
fi
else
if [ $x -le -10 -a $x -ge -100 ]
then
echo "$x is between -10 and -100"
else
echo "$x is between -1 and -9"
fi
fi
view raw nested.sh hosted with ❤ by GitHub


if..elif statements

Syntax
                if condition1
       then 
            statement1
       elif condition2
       then   
            statement2
       elfi condition3
       then 
            statement3
       else
            #if none of the conditions are satisfied
            statement4 
       fi


echo "Enter your favourite tech company"
read x
if [ -z $x ]
then
echo "You have entered a NULL string."
elif [ $x = "Apple" ]
then
echo "I guess you might be liking iphone and ipad "
elif [ $x = "Google" ]
then
echo "I guess you might be liking Android and Chrome"
elif [ $x = "Microsoft" ]
then
echo "I guess you might be liking Windows and Office"
elif [ $x = "Nokia" ]
then
echo "Sorry who Nokia?"
else
echo "Sorry search failed :( "
fi
view raw ifelif.sh hosted with ❤ by GitHub








No comments:

Post a Comment

Popular Posts