Thursday, March 22, 2012

UNIX TOOLS - Conditional : if else fi

Unix Tools and programming :
if else fi

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

For e.g. Write Script as follows:
$ vi isnump_n
#!/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
Try it as follows:
$ chmod 755 isnump_n

$ isnump_n 5

5 number is positive

$ isnump_n -45

-45 number is negative

$ isnump_n

./ispos_n : You must give/supply one integers

$ isnump_n 0

0 number is negative
Detailed explanation
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.

No comments:

Post a Comment