Conditional Constructs

There are two conditional constructs, if and case, which allow sequences of commands to be executed when certain conditions are met, or when a certain value matches a given pattern.

If Conditional Construct

The if command has the form,

if compound-list
then
   compound-list
[elif compound-list
then
   compound-list] ...
[else
   compound-list]
fi

The if compound-list is executed first; if its exit status is zero, the then compound-list is executed. Otherwise, each, if any, elif compound-list is be executed, in turn, and if its exit status is zero, the then compound-list for that elif block is executed. Otherwise, the else compound-list, if present, is executed.

Exit Status

The exit status of the if conditional construct is the exit status of whichever then or else compound-list is executed; if none is executed, the exit status is zero,

Case Conditional Construct

The case command executes a compound-list corresponding to the first of several patterns that is matched from the expansion of a given word; it has the form,

case word in
   pattern [ | pattern] ...) compound-list;;
   [pattern [ | pattern] ...) compound-list;;] ...
esac
  • The word undergoes all forms of expansion except for word splitting and pathname expansion.

  • Multiple patterns with the same compound-list can be combined with the “|” symbol. This is the only unquoted context where it is not recognized as the pipe operator.

  • The compound-list for each case must be terminated with the ;; operator, except for the last compound-list may omit it, since it is implicitly terminated by esac.

  • The entire case command is terminated with the esac (“case” reversed) reserved word.

Pattern matching rules are detailed in 2.13 Pattern Matching Notation. In summary,

  • ‘?’ matches any character

  • ‘*’ matches any sequence of characters, including an empty (null) string

  • ‘[…]’ bracket expressions work similarly to those used in regular expressions except that the ‘!’ character is used in place of ‘^’ to negate the bracket expression.

Exit Status

The exit status of the case conditional construct is zero if no pattern is matched; otherwise it is the exit status of the last command executed in the selected compound-list.

Warning

Notice that the exit status is always 0 for both if and case conditional constructs, if no compound-list is selected.