off by one for 2011 March 11 (entry 0)

< mairix rocks
libconfig problems in Debian and Ubuntu >

[Trackback URL for this entry] Fri Mar 11 11:32:26 getopts -- another one for posterity:

Just a little addition to posterity about getopts. 'getopts' is a handy bash builtin that parses parameter strings. It exists so parameters can be processed in a consistent way, and so you don't have to reinvent the wheel every time you want to use command line switches. It's part of POSIX, is really pretty easy to use, and many languages have libraries which work in a similar way. Anyway, there are many tutorials online, but the one at bash-hackers.org is the best I've seen for bash.

I was inspired to write this post because I've been wrestling with a problem. I used getopts inside a function that I was using for logging. It just wasn't working right and the behavior was strange. The answer, which perhaps should have been obvious in retrospect, is that getopts uses a variable, OPTIND, to index into the parameter list. You can use OPTIND to "shift off" the options you found with getopts, leaving the remainder.

This works great if you run getopts once, at the beginning of a script. But because of bash's scoping, if you use getopts inside a function, the value of OPTIND remains where it was left at the end of the previous getopts execution. So, if you're going to use getopts inside a function, you should reset OPTIND when finished or, to be safe, at the beginning of the function before running getopts.

I'm so glad I spent a few hours chasing that one down.

Update: It also implies that you should be mighty careful if you plan to use getopts in more than one place in the same execution of a program!

Filed under: technical:coding


[Main]

Unless otherwise noted, all content licensed by Peter A. H. Peterson
under a Creative Commons License.