63 lines
2.0 KiB
Bash
Executable File
63 lines
2.0 KiB
Bash
Executable File
#!/bin/bash
|
|
# ex33.sh: Exercising getopts and OPTIND
|
|
# Script modified 10/09/03 at the suggestion of Bill Gradwohl.
|
|
|
|
|
|
# Here we observe how 'getopts' processes command-line arguments to script.
|
|
# The arguments are parsed as "options" (flags) and associated arguments.
|
|
|
|
# Try invoking this script with:
|
|
# 'scriptname -mn'
|
|
# 'scriptname -oq qOption' (qOption can be some arbitrary string.)
|
|
# 'scriptname -qXXX -r'
|
|
#
|
|
# 'scriptname -qr'
|
|
#+ - Unexpected result, takes "r" as the argument to option "q"
|
|
# 'scriptname -q -r'
|
|
#+ - Unexpected result, same as above
|
|
# 'scriptname -mnop -mnop' - Unexpected result
|
|
# (OPTIND is unreliable at stating where an option came from.)
|
|
#
|
|
# If an option expects an argument ("flag:"), then it will grab
|
|
#+ whatever is next on the command-line.
|
|
|
|
NO_ARGS=0
|
|
E_OPTERROR=85
|
|
|
|
if [ $# -eq "$NO_ARGS" ] # Script invoked with no command-line args?
|
|
then
|
|
echo "Usage: `basename $0` options (-mnopqrs)"
|
|
exit $E_OPTERROR # Exit and explain usage.
|
|
# Usage: scriptname -options
|
|
# Note: dash (-) necessary
|
|
fi
|
|
|
|
|
|
while getopts ":mnopq:rs" Option
|
|
do
|
|
case $Option in
|
|
m ) echo "$OPTIND -$Option ($OPTARG)";;
|
|
n | o ) echo "$OPTIND -$Option ($OPTARG)";;
|
|
p ) echo "$OPTIND -$Option ($OPTARG)";;
|
|
q ) echo "$OPTIND -$Option ($OPTARG)";;
|
|
# Note that option 'q' must have an associated argument,
|
|
#+ otherwise it falls through to the default.
|
|
r | s ) echo "$OPTIND -$Option ($OPTARG)";;
|
|
* ) echo "Unimplemented option chosen.";; # Default.
|
|
esac
|
|
done
|
|
|
|
shift $(($OPTIND - 1))
|
|
echo "Rest $@"
|
|
|
|
# Decrements the argument pointer so it points to next argument.
|
|
# $1 now references the first non-option item supplied on the command-line
|
|
#+ if one exists.
|
|
|
|
exit $?
|
|
|
|
# As Bill Gradwohl states,
|
|
# "The getopts mechanism allows one to specify: scriptname -mnop -mnop
|
|
#+ but there is no reliable way to differentiate what came
|
|
#+ from where by using OPTIND."
|
|
# There are, however, workarounds. |