if.....else.....fi
If given condition is true then command1 is executed otherwise command2 is executed.
Syntax:
if condition then condition is zero (true - 0) execute all commands up to else statement else if condition is not true then execute all commands up to fi fi
eg
#!/bin/sh # # Script to see whether argument is positive or negative # if [ $# -eq 0 ] then echo "$0 : You must give/supply one integers" exit 1 fi
if test $1 -gt 0 then echo "$1 number is positive" else echo "$1 number is negative" fi
First script checks whether command line argument is given or not, if not given then it print error message as "./ispos_n : You must give/supply one integers". if statement checks whether number of argument ($#) passed to script is not equal (-eq) to 0, if we passed any argument to script then this if statement is false and if no command line argument is given then this if statement is true. The echo command i.e.
echo "$0 : You must give/supply one integers"
| |
| |
1 2
1 will print Name of script
2 will print this error message
And finally statement exit 1 causes normal program termination with exit status 1 (nonzero means script is not successfully run).
The last sample run $ isnump_n 0 , gives output as "0 number is negative", because given argument is not > 0, hence condition is false and it's taken as negative number. To avoid this replace second if statement with if test $1 -ge 0.
Nested if-else-fi
Syntax:
if condition then if condition then ..... .. do this else .... .. do this fi else ... ..... do this fi
osch=0
echo "1. Unix (Sun Os)"
echo "2. Linux (Red Hat)"
echo -n "Select your os choice [1 or 2]? "
read osch
if [ $osch -eq 1 ] ; then
echo "You Pick up Unix (Sun Os)"
else #### nested if i.e. if within if ######
if [ $osch -eq 2 ] ; then
echo "You Pick up Linux (Red Hat)"
else
echo "What you don't like Unix/Linux OS."
fi
fi
Multilevel if-then-else
Syntax:if condition then condition is zero (true - 0) execute all commands up to elif statement elif condition1 then condition1 is zero (true - 0) execute all commands up to elif statement elif condition2 then condition2 is zero (true - 0) execute all commands up to elif statement else None of the above condtion,condtion1,condtion2 are true (i.e. all of the above nonzero or false) execute all commands up to fi fi
# Script to test if..elif...else
#
if [ $1 -gt 0 ]; then
echo "$1 is positive"
elif [ $1 -lt 0 ]
then
echo "$1 is negative"
elif [ $1 -eq 0 ]
then
echo "$1 is zero"
else
echo "Opps! $1 is not number, give number"
fi