What do you use to support command-line arguments for BASH scripts?
What do you use to support command-line arguments in BASH scripts?
I have a script I want to add command-line arguments to. The platforms I need it to run on are Linux and OS X. The script-in-progress is currently here: https://gist.github.com/duganchen/7d...311e814d090ab4 I did google, but the results were honestly kind of overwhelming. I did find ArgBash, but honestly, I'm currently leaning towards getopts. What does this forum recommend? |
I use getopts.
Gah! That's what I get from posting at work. I use getopt, which is a GNU beast. Code:
info getopt |
I used getopts with a case statement.
https://github.com/bassmadrigal/scri...aster/sbgen.sh Code:
while getopts "hfw:d:m:D:M:r:" OPTION |
I am very happy with shflags. https://github.com/kward/shflags
I think internally it uses getopts as well, but eventually you don't have to do any parsing, and just check or use the parameters as entered. jlinkels |
I never got on with getopts: it doesn't handle gnu style long-options, nor options with optional arguments, and from what I've read its use can also differ between implementations.
I usually just code the option parsing manually, no surprises that way. |
Here is a simple portable example.
Code:
help='some help and documentation |
Quote:
nevertheless i've always been using it, just because it's built into bash. i should try getopt some day. |
Even when allowing for POSIX utility syntax conventions such as option combining it's really not hard to code manually, and as you say, it's not that much more long-winded or complex than the case statements employed by getopt(s).
Here's an example I wrote a few years back that follows -- to the best of my understanding -- all the POSIX guidelines, while also including support for GNU long-options. Not including the help, there are 3 example options (each in both long and short form): one with a mandatory argument, one with an optional argument and one without any argument (a basic flag). It uses no external utilities and no bashisms, just basic shell features. Code:
#!/bin/sh |
Quote:
|
Thanks all. I went with getopts.
The finished script is here: https://github.com/duganchen/md_preview |
All times are GMT -5. The time now is 05:24 PM. |