Thursday, October 18, 2007

Dealing with Getopts OPTIND variable and the dreaded double-hyphen

Hey There,

As some scripters out there know, a really easy way to parse options to your shell script is to use the getopts function, especially if you have a lot of options to process.

OPTIND - the automatic variable set to represent the index of options (sometimes shifted and subtracted by 1) is generally used to determine whether you've run out of options to process once getopts is finished.

Of course ksh has the double-hypen (--), which, if you enter it as an argument to a script, means "stop processing arguments" and populates OPTIND, thus making checking whether its empty, a non-bullet-proof way of telling if someone has passed no arguments to your script.

Fortunately, it's pretty easy to get around by just setting a counter variable (this is necessary, because getopts never gets the -- and, therefore, can't process it; it's handled by the shell first... bummer)

Here's an example using opts_selected as the name of my tracking variable (usage, in this example is a reference to function in the script that just prints out a usage message and exits):

opts_selected=0

while getopts c:hmo: option
do
case $option in
c)
opts_selected=1
;;
h)
usage
;;
k)
opts_selected=1
;;
m)
opts_selected=1
;;
o)
opts_selected=1
;;
\?)
usage
;;
*)
usage
;;
esac
done
if [ $opts_selected -eq 0 ]
then
WhateverCodeYouWantToPutHere
fi


Now you can be sure you're script is definitely not being passed any arguments, including the double-hyphen, before you proceed to write the remainder!

, Mike