Basic Linux Tutorial
Computer Tutorial

The if-then-fi Structure



The if-then-fi Structure

The if-then-fi structure is used to check a condition with the help of a test command. If the test returns a true value, then an action is performed. If the test returns a false value (not true), the action part of the program is not executed.

Synopsis :


if
      list A
then
      list B
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 zero (FALSE), jump to fi and continue with the first statement following the fi.

Flow chart of if-then-fi Structure

The if-then-fi Structure flowchart

Example of if-then-fi structure

if

test   -s   funfile

then

echo   funfile   exists

fi

echo   hello


The test command is commonly used to control the flow of control, but any command can be used, since all Linux system commands generate a return code