Main index

Introducing UNIX and Linux


More on shells

Overview
Simple arithmetic
      Arithmetic expansion
            Operators for arithmetic expansion
      The 'expr' command
Pattern matching
      Patterns
            Examples of patterns
      The case statement
Entering and leaving the shell
More about scripts with options
Symbolic links
Setting up terminals
Conventions used in UNIX file systems
Summary
Exercises

Answer to chapter 8 question 9

This could be solved using pattern matching on the arguments, but since there are many possibilities for running eurhello with options, the clean way to solve the problem is with getopts.

# Set the string GREETING to the usual greeting
GREETING="Hello"

# Use getopts to go through the possible options
# These can be f or g, or G followed by an argument
# An option is stored in OPTIONNAME when encountered
while getopts fgG: OPTIONNAME
do
   # Check the three possibilities
   case "$OPTIONNAME" in
           # French
        f) GREETING="Bonjour";;
           # German
        g) GREETING="Guten Tag";;
           # Argument to -G held in OPTARGS
        G) GREETING="$OPTARG";;
   esac
done

# If the script is called with invalid options,
# getopts will discard them and display an error
# message

# Now get rid of the options which have been processed
shift $(( $OPTIND - 1 )

# Check a name string is an argument to the script
if [ $# -eq 0 ]
then echo "usage: $0 [-f] [-g] [-G greeting] name"
     exit 1
fi

# Finally, produce the output
echo "$GREETING $*"

Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck