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



The if...else...fi statement is the next form of control statement that allows Shell to execute statements in a controlled way and make the right choice.

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

The Shell expression is evaluated in the above syntax. If the resulting value is true, given statement(s) are executed. If the expression is false, then no statement will be executed.

Example

The above example can also be written using the 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

Upon execution, you will receive the following result −

a is not equal to b
unix-decision-making.htm
Advertisements