Nested if-else-fi

The if-else construct can be nested. For example, the following is a nested if conditional that displays the corresponding of a day:


echo -n "Enter value in range of 1 to 7 : "
read a
if [ $a -eq 1 ];
then
         echo "Sunday"
else if [ $a -eq 2 ];
then
         echo "Monday"
else if [ $a -eq 3 ];
then
         echo "Tuesday"
else if [ $a -eq 4 ];
then
         echo "Wednesday"
else if [ $a -eq 5 ];
then
         echo "Thursday"
else if [ $a -eq 6 ];
then
         echo "Friday"
else if [ $a -eq 7 ];
then
         echo "Saturday"
else
         echo "You entered an invalid number"
fi fi fi fi fi fi fi



The else if can be replaced by elif, i.e. elif is a constructor of else if. Therefore above sequence can be written as:


echo -n "Enter value in range of 1 to 7 : "
read a
if [ $a -eq 1 ];
then
         echo "Sunday"
elif[ $a -eq 2 ];
then
         echo "Monday"
elif[ $a -eq 3 ];
then
         echo "Tuesday"
elif[ $a -eq 4 ];
then
         echo "Wednesday"
elif[ $a -eq 5 ];
then
         echo "Thursday"
elif[ $a -eq 6 ];
then
         echo "Friday"
elif[ $a -eq 7 ];
then
         echo "Saturday"
else
         echo "You entered an invalid number"
fi


 Note : that elif did not require a corresponding terminating fi statment.

0 Comments:

Post a Comment