Let’s say you want to use getopts to parse ARGV in bash. Let’s say you also want a non-getopts argument. For example:
./foo.sh argument
./foo.sh -x argument
./foo.sh -abx argument
The non-optional argument is here always given as the last argument.
So, how do you retrieve that last argument after getopts is finished doing its work? Check it out, yo:
while getopts "ghr" opt; do
case $opt in
h)
help_message
;;
g)
GIT_DEPLOY=true
;;
r)
RSYNC_DEPLOY=true
;;
\?)
echo "Invalid option handed in. Usage:"
help_message
;;
esac
done
OPTIONS=${@:$OPTIND}
That last line is the magic. getopts sets $OPTIND to be the index of the last valid option. Index bash’s ARGV, fondly known as $@, in the position of $OPTIND and you’ll get the last item from ARGV.