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

UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 45.32 A Better read Command: grabchars Chapter 45
Shell Programming for the Initiated
Next: 45.34 Arrays in the Bourne Shell
 

45.33 Testing Two Strings with One case Statement

The shell's case statement (44.5 ) has some advantages over the test command (44.20 ) - for instance, case can do pattern matching. But test has the -a and -o "and" and "or" operators; those don't seem easy to do with case . And test isn't built in to some older shells, so using case may be faster.

Here's a way to test two things with one case statement. It won't solve all your problems. If you think carefully about the possible values the variables you're testing can have, though, this might do the trick. Use a separator (delimiter) character between the two variables.

In the example below, I've picked a slash (/ ). You could use almost any character that isn't used in case pattern matching (44.6 ) and that won't be stored in either $# or $1 . The case below tests the command-line arguments of a script:

case "$#/$1" in
1/-f) redodb=yes ;;
0/) ;;
*)  echo "Usage: $myname [-f]" 1>&2; exit 1 ;;
esac

If there's one argument ($# is 1 ) and the argument ($1 ) is exactly -f , the first pattern matches, and the redodb variable is set. If there's no argument, $# will be 0 and $1 will be empty, so the second pattern matches. Otherwise, something is wrong; the third pattern matches, the script prints an error and exits.

Of course, you can do a lot more this way than just testing command-line arguments.

- JP


Previous: 45.32 A Better read Command: grabchars UNIX Power Tools Next: 45.34 Arrays in the Bourne Shell
45.32 A Better read Command: grabchars Book Index 45.34 Arrays in the Bourne Shell

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










??????????????@Mail.ru