Introducing UNIX and Linux |
More on shellsOverview |
Answer to chapter 8 question 9This could be solved using pattern matching on the arguments,
but since there are many possibilities for running
# 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