getopts and argv in bash

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.

Author: jamandbees

There's just this whole, like, wha? Out there in the world, y'know? The jam and the bees, please.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: