Conditional Statements#

The basic structure of conditionals is similar to most other programming languages:

if test1; then    # if "test1 has exit code 0" then
   # block 1        
elif test2; then  # else if "test2 has exit code 0" then
   # block 2
else              # else
   # block 3
fi

Here test1 and test2 can be any shell command. The exit code is evaluated, and only exit code 0 is treated as “true” and the subsequent block is executed. Any other exit code is handled as “false”.

More complex logical conditions, e.g. negations or conjunctions, have to be built into the test commands.

There can be any number of elif (else if) blocks, or none at all. Also the last catch-all else-block is optional. The fi statement (if spelled backwards) closes the if block.

Note

Depending on the style, the statement can be split into multiple lines, this makes the semicolons superfluous:

if test1
then
   # block1
elif test2
then
   # block2
fi

The most compact form would be everything on one line. In this case additional semicolons are needed:

if test1 ; then ... ; elif test2 ; then ... ; fi

Often there are spaces around the semicolons to increase readability, but their are not strictly necessary.