Basic Linux Tutorial
Computer Tutorial

The if-then-else-fi Structure



The if-then-else-fi Structure

This structure is used when you want to perform one of two actions, depending on the result of a test. The if-else construct allows you to execute one set of commands if the return code of the controlling command is 0 (true) or another set of commands if the return code of the controlling command is non-zero (false).

Synopsis :


if
      list A
then
      list B
else
      list C
fi

A summary of the execution of the if construct is as follows :

1. Command list A is executed.
2. If the return code of the last command in command list A is a 0 (TRUE), execute command list B, then continue with the first statement following the fi.
3. If the return code of the last command in command list A is not 0 (FALSE), execute command list C, then continue with the first statement following the fi.

Flow chart of if-then-else-fi Structure

The if-then-else-fi Structure flowchart

if  [ “$X” -lt 10 ]
then

echo   X is less than 10

else

echo   X is not less than 10

fi