Name
case
Synopsis
casevalue
inpattern1
)cmds1
;;pattern2
)cmds2
;; . . . esac
Execute the first set of commands (cmds1)
if value matches pattern1,
execute the second set of commands (cmds2) if
value matches pattern2,
etc. Be sure the last command in each set ends with ;;
. value is
typically a positional parameter or other shell variable.
cmds are typically Unix commands, shell
programming commands, or variable assignments. Patterns can use
file-generation metacharacters. Multiple patterns (separated by
|
) can be specified on the same
line; in this case, the associated cmds are
executed whenever value matches any of these
patterns. See the Examples here and under eval.
The shell allows pattern to be preceded
by an optional open parenthesis, as in (
pattern
)
. In Bash, it's necessary for balancing
parentheses inside a $( )
construct. See also the nocasematch
option in Shell Options.
Examples
Check first command-line argument and take appropriate action:
case $1 in # Match the first arg no|yes) response=1;; -[tT]) table=TRUE;; *) echo "unknown option"; exit 1;; esac
Read user-supplied lines until user exits:
while : # Null command; always true do printf "Type . to finish ==> " read line case "$line" in .) echo "Message done" break ;; *) echo "$line" >> $message ;; esac done
Get bash Quick Reference 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.