Unix Shell - The if...else...fi statement

Advertisements


The if...else...fi statement is the next form of control statement that allows Shell to execute statements in more controlled way and making decision between two choices.

Syntax:

if [ expression ]
then
   Statement(s) to be executed if expression is true
else
   Statement(s) to be executed if expression is not true
fi

Here Shell expression is evaluated. If the resulting value is true, given statement(s) are executed. If expression is false then no statement would be not executed.

Example:

If we take above example then it can be written in better way using if...else statement as follows:

#!/bin/sh

a=10
b=20

if [ $a == $b ]
then
   echo "a is equal to b"
else
   echo "a is not equal to b"
fi

This will produce following result:

a is not equal to b


Advertisements
Advertisements