The if Statement

The if statement performs actions depending on whether a given condition is true or false. The if statement uses the return code of a command to determine whether a condition is true or false. A return code of zero is treated as true, whereas a non-zero return code is treated as false. The syntax of the if statement is as follows:

if list1
then
   list2
elif list3
then
   list4
else
   list5
fi

Both the elif and the else statements are optional. If you have an elif statement, you don't need an else statement and vice versa. An if statement can be written with any number of elif statements.

Because the if statement is treated as a list, it can be also written on a single line:

if list1 ; then list2 ; elif list3 ; then list4 ; else  ...

Get Sams Teach Yourself Shell Programming in 24 Hours, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.