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.

Advertisements

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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s