GNU getopt Needs A Helper

So, recently at work, I found myself knee deep in… scripts…

Most of my scripts had ugly positional parameters/arguments (you know, $1 was the value for this, $2 was the input for that)… So, I dug up getopt… But then I quickly spiralled down the time-sucking rabbit hole of trying to automate some other bits, like being able to print the “usage” by “simply” plucking out all the options given to getopt in the first place…

Nope, NOT getopts; Nope, NOT POSIX Either…

I am fully aware of the difference between the BASH in-built getopts versus the GNU versus the POSIX variety (here’s looking at you, OSX). We’re talking about the GNU variety here, to enable use of --long “long options” type.

So, one badly burnt weekend later, I have the basis of all my future scripts: I offer you my getopt_helper.sh version 1.0, replete with a “self documenting” “usage guide” – you only need to “override” (i.e. define a BASH function with a specific name) that will print out a summary description of what your script does, and the actual options and expected arguments will be “automagically” printed…

The functionality of the getopt_helper.sh script is mainly to:

  • use arrays to specify the short and long options, as well as any specific (required or optional) arguments, instead of manually hard-coding the list with the call to getopt
  • while using the arrays, as per the previous point, to be able to easily print out the usage of the script

You can use the attached getopt_helper_test.sh as an example of a script that you will actually write to use getopt_helper.sh.

Meanwhile, I am aiming for v2.0 of the script to “auto-document” a skeletal while...do...done arguments parsing loop itself if you run it with configured “overridden” arrays but also with some specific option…

2019/04/13 Update: I pulled the files off here and actually “GitHub’d” this – feel free to make corrections/improvements!

Leave a Reply