Each time you type a command line at a shell prompt, you can see what happens and decide what command to run next. But a shell script needs to make decisions like that itself. A case statement helps the script make decisions. A case statement compares a string (usually taken from a ) to one or more patterns. The patterns can be simple strings (words, digits, etc.) or they can be . When the case finds a pattern that matches the string, it executes one or more commands.
Here's an example. It tests yourenvironment variable. If you're using a vt100 or tk4023 terminal, it runs a command to send some characters to your terminal. If you aren't on either of those, it prints an error and quits:
case "$TERM" in vt100) echo 'ea[w' | tr 'eaw' '\033\001\027' ;; tk4023) echo "*[p23" ;; *) # Not a VT100 or tk4023. Print error message: echo "progname: quitting: you aren't on a VT100 or tk4023." 1>&2 exit ;; esac
Here are more details about how this works.
The statement compares the string between the words
in to the strings at the left-hand edge of the
lines ending with a
) (right parenthesis) character.
If it matches the first case (in this example, if it's the
the command up to the
;; is executed.
;; means "jump to the
esac" (esac is "case"
You can put as many commands as you want before each
put each command on a separate line (or separate commands on a line with
If the first pattern doesn't match, the shell tries the next
case - here, tk4023.
As above, a match runs the command and jumps to the esac.
The next pattern is the wildcard
It matches any answer other than vt100 or tk4023
(such as xterm or an empty string).
You can use as many patterns as you want to. The first one that matches is used. It's okay if none of them match. The style doesn't matter much. Pick one that's readable and be consistent.