If Statements

If statements test conditions and execute commands when the condition is true. The if statement has the following general format:

if [ condition ]
  then
     commands
elif [ condition ]
  then
     commands
else
     commands
fi

The if statements begins with if and ends with fi (if spelled backward). All three parts are not required. Only the if section is required. The elif (elseif) and the else sections are optional. Also, notice that the if section and the elif section start with then, but the else section does not. You can use more than one elif section, but only one if and else section is allowed. An if statement can be as simple as:

if [ $x -eq 1 ]
  then
    echo Hello
fi

A more complex statement is:

 if [ $day = "Saturday" -o $day = "Sunday" ...

Get Spring Into Linux® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.