I would like to parse long options in a shell script. POSIX only provides getopts to parse single letter options. Does anyone know of a portable (POSIX) way to implement long option parsing in the shell? I’ve looked at what autoconf does when generating configure scripts, but the result is far from elegant. I can live with accepting only the full spellings of long options. Single letter options should still be allowed, possibly in groups.
I’m thinking of a shell function taking a space separated list of args of the form option[=flags], where the flags indicate that the option takes an arg or can be specified multiple times. Unlike its C counterpart there is no need to distinguish between strings, integers and floats.
Design notes towards a portable shell
getopt_longcommandI have a program
getoptxwhich works with single-letter options (hence it is not the answer to your problem), but it handles arguments with spaces correctly, which the originalgetoptcommand (as opposed to the shell built-ingetopts) does not. The specification in the source code says:I recommend the
eval set -- $(getopt_long "$optspec" "$@")notation for yourgetopt_long.One major issue with
getopt_longis the complexity of the argument specification — the$optspecin the example.You may want to look at the notation used in the Solaris CLIP (Command Line Interface Paradigm) for the notation; it uses a single string (like the original
getopt()function) to describe the options. (Google: ‘solaris clip command line interface paradigm’; using just ‘solaris clip’ gets you to video clips.)This material is a partial example derived from Sun’s
getopt_clip():