How to parse options in Bash

I needed to parse some options in a bash script. I was always using GNU getopt external program. It's portable, old and buggy, yet it can handle both short (-x) and long (--extra) options. More info can be found in it's man page:

# man getopt

Anyway, this is cool, but I just wanted short options and did not want to rely on external command. What were the options? Well, there is a bash built-in called getopts. Note the trailing "s". More info can be found in the bash manual page:

# man getopts

It shows you "the long one; the bash one", you have been warned. Using it is as easy as:

while getopts ":f" opt; do

case $opt in
f)
FORCE=1
;;
\?)
echo "Invalid option: -$OPTARG" >&2
;;
esac
done

I was not aware about the bash built-in. Although it does not support long options, I like it very much.
22 August 2011 | bash
twitter.com linkedin.com
google.com/+ facebook.com
flickr.com youtube.com