home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 44.4 Testing How Your System Executes Files Chapter 44
Shell Programming for the Uninitiated
Next: 44.6 Pattern Matching in case Statements
 

44.5 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 (6.8 , 6.1 ) ) to one or more patterns. The patterns can be simple strings (words, digits, etc.) or they can be case wildcard expressions (44.6 ) . When the case finds a pattern that matches the string, it executes one or more commands.

Here's an example. It tests your TERM (5.10 ) 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:


echo...\027'
 


1>&2
 
exit
 

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 (8.5 ) ).

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.

- JP


Previous: 44.4 Testing How Your System Executes Files UNIX Power Tools Next: 44.6 Pattern Matching in case Statements
44.4 Testing How Your System Executes Files Book Index 44.6 Pattern Matching in case Statements

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System