The case Statement
If you need to check a variable for one of many values,
you could use a cascading series of if
and elif
tests, together with test:
if [ "X$1" = "X-f" ] then ... Code for -f option elif [ "X$1" = "X-d" ] || [ "X$1" = "X--directory" ] # long option allowed then ... Code for -d option else echo $1: unknown option >&2 exit 1 fi
However, this is awkward to write and difficult to read. (The
>&2
in the echo command sends the output to standard
error. This is described in Section 7.3.2.) Instead, the
shell's case
construct should be used
for pattern matching:
case $1 in -f) ... Code for -f option ;; -d | --directory) # long option allowed ... Code for -d option ;; *) echo $1: unknown option >&2 exit 1 # ;; is good form before `esac', but not required esac
As can be seen, the value to be tested appears between case
and in
. Double-quoting the value, while not
necessary, doesn't hurt either. The value is tested against each list of
shell patterns in turn. When one matches, the corresponding body of
code, up to the ;;
, is executed.
Multiple patterns may be used, separated by the |
character, which in this context means "or."
The patterns may contain any shell wildcard characters, and variable,
command, and arithmetic substitutions are performed on the value before
it is used for pattern matching.
The unbalanced right parenthesis after each pattern list is perhaps surprising; this is the only instance in the shell language of unbalanced delimiters. (In Section 14.3.7, we will see ...
Get Classic Shell Scripting 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.