# The if-then-else Statement - Shell Scripting

In the if-then statement, you only have one option of whether or not a command is successful.
If the command returns a non-zero exit status code, the bash shell just moves on to the next command in the script. In this situation, it would be nice to be able to execute an alternate set of commands. That’s exactly what the if-then-else statement is for.

The if-then-else statement provides another group of commands in the statement:

if command
then
commands
else
commands
fi

If the command in the if statement line returns with an exit status code of zero, the commands listed in the then section are executed, just as in a normal if-then statement. If the command in the if statement line returns a non-zero exit status code, the bash shell executes the commands in the else section.

Now you can modify the test script to look like this:

$cat test4 #!/bin/bash # testing the else section testuser=badtest if grep$testuser /etc/passwd
then
echo The files for user $testuser are: ls -a /home/$testuser/.b*
else
echo The user name $testuser doesn’t exist on this system fi$ ./test4
The user name badtest doesn’t exist on this system
\$

That’s more user-friendly. Just like the then section, the else section can contain multiple commands. The fi statement delineates the end of the else section.