Introducing UNIX and Linux |
More on shellsOverview |
The case statementA statement that involves pattern matching is
where expression has a value (and would typically be a
variable preceded by
pattern and the case $1 in *.c) printf "%s: %s\n" "$1" "c program text" ;; *.a) printf "%s: %s\n" "$1" "archive library" ;; *.o) printf "%s: %s\n" "$1" "object file" ;; *) printf "%s: %s\n" "$1" "unknown type" ;; esacWhere patterns appear in a case statement they are
matched with the expression at the start of the case
statement, and not with any filenames. If a pattern appears within
a command-list in a case statement, however, the
pattern is matched to filenames as before. Double semicolons are
required, because a single semicolon is used to separate multiple
commands occurring on a single line. The following script lists the
files in the current directory, but asks you whether you wish to
list the 'dot' files:
echo "List dot files as well? " # Prompt user read YESORNO # Read reply case "$YESORNO" in # Check reply [Yy]*) ls * .* ;; # Commence with a Y? [Nn]*) ls * ;; # Commence with an N? *) echo "Sorry, don't understand";; esac Note the technique used here for asking the user a yes/no
question - the answer is assumed to commence with a Worked exampleWrite a script named # First, check we do have a single argument case $# in 1) ;; *) echo "$0: Incorrect number of arguments";; esac # Now examine the suffix of argument 1 case $1 in *.c) cc $1 ;; *.p) pc $1 ;; *.f) f77 $1 ;; *) echo "Unknown language";; esac The names for the compilers may be different on your system, and are not specified in POSIX. Where the same command is required for two separate patterns, rather than duplicating the line (or lines) of commands, you can combine the two (or more) patterns. So the pattern sam|chris would match either Worked exampleWrite a script to read in a string representing a telephone
number as dialled from the UK, and indicate whether it is an
overseas number (commencing # Prompt user and read in the number printf "Input phone number: " read N # Examine the various patterns that might match N case $N in 00*|010*) echo "International" ;; 0898*|0891*) echo "Value added" ;; 0800*) echo "Freephone" ;; 1??) echo "Service number" ;; 0?????????) echo "National code (pre 1995)" ;; 01?????????) echo "National code (after 1995)" ;; *) echo "Unknown code" ;; esac |
Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck