Linux Shell Scripting Tutorial (LSST) v1.05r3 | ||
Chapter 3: Shells (bash) structured Language Constructs | ||
|
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
For e.g. Write Script as follows:
$ vi isnump_n
|
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.
You can write the entire if-else construct within either the body of the if statement of the body of an else statement. This is called the nesting of ifs.
|
Run the above shell script as follows:
$ chmod +x nestedif.sh
$ ./nestedif.sh
1. Unix (Sun Os)
2. Linux (Red Hat)
Select you os choice [1 or 2]? 1
You Pick up Unix (Sun Os)
$ ./nestedif.sh
1. Unix (Sun Os)
2. Linux (Red Hat)
Select you os choice [1 or 2]? 2
You Pick up Linux (Red Hat)
$ ./nestedif.sh
1. Unix (Sun Os)
2. Linux (Red Hat)
Select you os choice [1 or 2]? 3
What you don't like Unix/Linux OS.
Note that Second if-else constuct is nested in the first else statement. If the condition in the first if statement is false the the condition in the second if statement is checked. If it is false as well the final else statement is executed.
You can use the nested ifs as follows also:
Syntax:
if condition then if condition then ..... .. do this else .... .. do this fi else ... ..... do this fi
| ||
test command or [ expr ] | Multilevel if-then-else |