35.10. Test String Values with Bourne-Shell case
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 shell or environment variable (Section 35.9, Section 35.3)) to one or more patterns. The patterns can be simple strings (words, digits, etc.) or they can be case wildcard expressions (Section 35.11). When the case statement finds a pattern that matches the string, it executes one or more commands.
Here's an example that tests your TERM (Section 5.2) environment 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:
exit Section 35.16
+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 case and 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 vt100), the command up to the ;; is executed. The ;; means "jump to the esac" (esac is "case" spelled backwards). You can put as many commands as you want before each ;;, but put each command on a separate line (or separate commands on a line with semicolons (Section 28.16)).
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. No match? 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.
Copyright © 2003 O'Reilly & Associates. All rights reserved.