UNIX and Linux Shell "If" Control Flow

The "If" control flow is used to execute a command list only if a given command returns zero.

The general form is:


if command1 
then
	command2
else
	command3
fi

If command1 returns zero (success status of a command or test) then command2 is executed. Otherwise command3 is executed.

Nested if statements can also be used.


if command1 
then
	command2
else
	if command3
	then
		command4
	fi
fi

This can also be written using the abbreviated form:


if command1 
then
	command2
elif command3
then
	command4
fi

Both these statements execute command2 if command1 returns zero. If command1 returns non-zero and command3 does return zero, then command4 is executed.

Our page on Test Operators has some examples on using the "test" command to test for conditions, however, we can explore one complicated case here.

"If" Example: Solfège

In this example we read in the answers to two questions, then check the answers using an if loop and a nested if loop.


echo "Test 1: What is a female dear called?"
read answer1
echo "Test 2: What is a long long way to go?"
read answer2

if test "$answer1" = "doe"
then
        echo "You passed test 1"
        if test "$answer2" = "far"
        then
                echo "and you also passed test 2"
        else
                echo "but you failed test 2"
        fi
elif test "$answer2" = "far"
then
        echo "You failed test 1 but passed test 2"
else
        echo "You failed both test 1 and test 2"
fi

If the above is written to a file called ifexam and run by a clever user we get the following:

sh$ sh ifexam
Test 1: What is a female dear called?
doe
Test 2: What is a long long way to go?
far
You passed test 1
and you also passed test 2

Perhaps you can trace through the if loops and see what would happen if one or both of the answers were incorrect!