Introducing UNIX and Linux |
More on shellsOverview |
More about scripts with optionsWriting a script with arguments is straightforward - you just
need to examine An option is an argument that commences with a hyphen. Suppose you wanted to write a command
You could check whether mycommand -h mycommand -a mycommand -ah mycommand -ha mycommand -a -h mycommand -h -a in addition to any invalid options it might be presented with.
The utility
while getopts h OPTIONNAME
do
case $OPTIONNAME in
h) echo 'Usage: mycommand [-h]' ;;
?) echo 'Bad option to mycommand'
exit 1 ;;
esac
done
echo "Arguments were $@"
The action
In the case of Some commands take options that require arguments - such as
If an option requires an argument, then a colon should follow
the option name in the list of allowed options to
MESSAGE=Hello # Variable to store message
if getopts m: OPTIONNAME # If an option found
then
case $OPTIONNAME in # Check which option found
m) MESSAGE=$OPTARG;;
?) exit 1;; # Exit if not -m
esac
fi
echo $MESSAGE # Output the message
The number of the next argument to be processed by
Worked exampleWrite a script
Solution: Use
SUBJECT=""
if getopts s: OPTNAME # Valid option is 's'
then # which takes an argument
case $OPTNAME in
s) SUBJECT="$OPTARG";; # The argument to 's' is
# SUBJECT
?) echo "Usage: $0 [-s subject] users"
exit 1;; # Exit if invalid option
esac
fi
shift $(($OPTIND - 1)) # Remove the options
USERS="$*" # The rest of the line
# is the recipients
if [ -z "$USERS" ] # ... which is compulsory
then echo "Must specify recipients"
exit 1 # Exit if no recipients
fi
while [ -z "$SUBJECT" ] # Loop until subject
do # is not null
printf "Subject (no quotes): "
read SUBJECT
done
mailx -s "$SUBJECT" $USERS"
If you intend to write scripts which require options, then using
|
Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck