Unix Shell - The if...fi statement

Advertisements


The if...fi statement is the fundamental control statement that allows Shell to make decisions and execute statements conditionally.

Syntax:

if [ expression ]
then
   Statement(s) to be executed if expression is 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. Most of the times you will use comparison operators while making decisions.

Give you attention on the spaces between braces and expression. This space is mandatory otherwise you would get syntax error.

If expression is a shell command then it would be assumed true if it return 0 after its execution. If it is a boolean expression then it would be true if it returns true.

Example:

#!/bin/sh

a=10
b=20

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

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

This will produce following result:

a is not equal to b


Advertisements
Advertisements