Getops
getopts processes the positional parameters of the parent command. In bash, this is stored in the shell variable “$@”.
Positional parameters
A positional parameter is an argument specified on the command line, used to launch the current process in a shell.
Positional parameter values are stored in a special set of variables maintained by the shell.
mycmd -a argument1 -b argument2
EXAMPLES
The following code fragment shows how one might process the arguments for a command that can take the options -a and -b, and the option -o, which requires an argument.
args=`getopt abo: $*`
if [ $? -ne 0 ]; then
echo 'Usage: ...'
exit 2
fi
set -- $args
while :; do
case "$1" in
-a|-b)
echo "flag $1 set"; sflags="${1#-}$sflags"
shift
;;
-o)
echo "oarg is '$2'"; oarg="$2"
shift; shift
;;
--)
shift; break
;;
esac
done
echo "single-char flags: '$sflags'"
echo "oarg is '$oarg'"
Last updated on