Happy Diwali

Wishing you a safe and happy Diwali

Introduction to Shell Programming: Conditional Statements

#!/bin/sh

echo "Enter Your Name:"
read name

if [ $name = 'Linux' ]
then
	echo "**My Name is also Linux!**"
fi

echo "Is it (1)Morning or (2)Evening?"
read time

if [ $time = 1 ]
then
	echo "Good Morning" $name
else
   echo "Good Evening" $name
fi

echo "***********Menu***********"
echo "*                        *"
echo "* 1) Start               *"
echo "* 2) Stop                *"
echo "* 3) Quit                *"
echo "*                        *"
echo "**************************"
read choice

if [ $choice = 1 ]
then
   # This is how we can display " quotes
   # inside quotes. This is known as
   # character escaping
   echo "You chose \"Start\""
elif [ $choice = 2 ]
then
   echo "You chose \"Stop\""
elif [ $choice = 3 ]
then
   echo "You chose \"Quit\""
else
   echo "Wrong choice!"
fi

The above code illustrates the main structure of three kinds of conditional statements; if-then, if-then-else, if-then-el(se)if-then-else. Obviously the if-then statement has the following form:

if [ CONDITION ]
then
   ...DO THIS...
fi

The if block ends with the word fi. In shell some statement blocks end with such kind of “reverse” words. For example, case block (like switch in C/C++) ends with the word esac which is the reverse of case.

In C/C++, the above would have looked like the following:

if (CONDITION)
{
   ...DO THIS...
}

Spaces after the strting [ and before the ] are a MUST. The other way of writing the above condition is like the following :

if test CONDITION
then
   ...DO THIS...
fi

Definitely, the statement with the [] looks more structured like in other programming languages therefore is widely used. However, the need for space and before square brackets feels a bit awkward to some but let’s not ge into this debate and try to learn a way to remember this rule, just think that [ is a replacement for test (in if test $a = 2) and as you must have space after test, so is for [ (you can’t write if test$a = 2, can you?). The ending ] is just for readability. I read this in some book.

The other type of conditional statement, if-then-else and if-then-el(se)if-then-else don’t require further explanation. Just understand what makes a block in those statements. The following illustration will clear this:

if-then-else Block Illustration
FIG.: if-then-else Block Illustration

  
Home |  About