Sunday, April 12, 2009

if else construct in shell script

The syntax of if ... else statement is,

if condition
then
do something
else
do something
fi

If the condition of if statement is true then, all commands up to else statement is executed and then control is returned to after fi statement.

If the condition of if condition is false then, else block is executed upto statement fi.

Note that if condition can be nested, suppose within one if another if may be existed, within else another if may be existed but they follow the same construct.

With a simple example I will give an example of if ... else construct. From console script will ask the person age. If age is served over 50 it will display a message if not then else block is executed and another message will shown.

# cat if_else_age.txt

echo -n "Enter you age :"
read age
if test $age -gt 50
then
echo "You are an old man"
else
echo "You are not at least old man"
fi

# chmod +x if_else_age.txt

# ./if_else_age.txt
Enter you age :56
You are an old man

# ./if_else_age.txt
Enter you age :23
You are not at least old man

if -elif -else construct in shell script
Multilevel if -then -else construct can be achieved by if -elif -else construct. The syntax is,

if condition1
then
if condition1 is true then execute all commands up to elif
statement and control return after fi
elif condition2
then
if condition2 is true then execute all commands up to elif
statement and control return after fi
elif condition3
then
if condition3 is true then execute all commands up to elif
statement and control return after fi
#................Any number of elif can be repeated here
else
if all condition1, condition2, condition3 became false or
condition return nonzero value then execute all commands up to
fi.
fi


An example is listed below. User will be prompted to press an age and based on the input with an if -elif -else example it will show a message.

# cat if_elif.sh

echo -n "Enter our age : "
read age
if [[ $age -ge 0 && $age -le 10 ]]
then
echo "You are still child"
elif [[ $age -gt 10 && $age -le 50 ]]
then
echo "You are young"
elif [[ $age -gt 50 && $age -le 140 ]]
then
echo "You are old man"
else
echo "You pressed invalid age."
fi

# ./if_elif.sh
Enter our age : 34
You are young

# ./if_elif.sh
Enter our age : 87
You are old man

# ./if_elif.sh
Enter our age : 3
You are still child

# ./if_elif.sh
Enter our age : 180
You pressed invalid age.
Related Documents
http://arjudba.blogspot.com/2009/04/checking-condition-in-shell-scipt-by.html

No comments:

Post a Comment