I want to make my bash script deal with long parameters. I found getopt
, but it isn't supported in OS X. Can anyone tell me why getopt
was implemented by BSD, but not GNU? I tried building getopt
in GNU C lib, but it failed for my poor skills with Linux.
Did anyone do this work?
On Unix-like operating systems, getopts is a builtin command of the Bash shell. It parses command options and arguments, such as those passed to a shell script.
Description. The getopts command is a Korn/POSIX Shell built-in command that retrieves options and option-arguments from a list of parameters. An option begins with a + (plus sign) or a - (minus sign) followed by a character. An option that does not begin with either a + or a - ends the OptionString.
The main differences between getopts and getopt are as follows: getopt does not handle empty flag arguments well; getopts does. getopts is included in the Bourne shell and Bash; getopt needs to be installed separately. getopt allows for the parsing of long options ( --help instead of -h ); getopts does not.
There is a brew bottle for getopt.
Just run brew install gnu-getopt
.
You can either specify the path for it like /usr/local/Cellar/gnu-getopt/1.1.6/bin/getopt
Or use brew link --force gnu-getopt
so it will be linked in /usr/local/bin/
Just be aware that forcing linking might be corrupting your system (as it replaces the system getopt by the gnu one).
See also other answer suggesting to define FLAGS_GETOPT_CMD
.
I recommend using Homebrew to install gnu-getopt
and then adding $FLAGS_GETOPT_CMD
to your ~/.bash_profile
file to specify the cmd path for getopt, pointing at the homebrew location, like so:
brew install gnu-getopt
Then follow directions from brew to add to your local path:
sudo echo 'export PATH="/usr/local/opt/gnu-getopt/bin:$PATH"' >> ~/.bash_profile
Then you can add FLAGS_GETOPT_CMD
:
sudo echo 'export FLAGS_GETOPT_CMD="$(brew --prefix gnu-getopt)/bin/getopt"' >> ~/.bash_profile
Open a new terminal, or run . ~/.bash_profile
in existing terminal to load changes
Run echo $FLAGS_GETOPT_CMD
to confirm it was actually set in your console
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With