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

Unix Power ToolsUnix Power ToolsSearch this book

36.25. Testing Two Strings with One case Statement

The shell's case statement (Section 35.10) has some advantages over the test command (Section 35.26) -- 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 (Section 35.11) 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: $0 [-f]" 1>&2; exit 1 ;;

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

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.