Nested if-else-fi in Linux Shell Script

By: Dorris Viewed: 154828 times  Printer Friendly Format    


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.

$ vi nestedif.sh
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

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 elsestatement 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


Most Viewed Articles (in Linux )

Latest Articles (in Linux)

smskannel SMS gateway run in background

Running jar files in background in ssh window

Could not open '': No such file or directory at lib/ExtUtils/MM_Unix.pm line 2697

Can't locate ExtUtils/MakeMaker.pm in @INC ...

bash: make: command not found

apxs: command not found

bash: svn: command not found

make: Nothing to be done for `all'.

How to burn your CD / DVD ISO image using Media Creator (Adaptec/Roxio) on Windows

How to burn your CD / DVD ISO image using Nero Burning ROM (Ahead Software) on Windows

How to burn your CD / DVD ISO image using Nero Express (Ahead Software) on Windows

How to burn your CD / DVD ISO image using NISO Recorder V2 Power Toy on Windows

How to burn your CD / DVD ISO image using k3b on CentOS

Compiling and Installing software from source in Linux

Installing RPM's using the Redhat Package Manager in Linux

Comment on this tutorial