Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make bash deal with long param using "getopt" command in mac?

Tags:

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?

like image 361
qiushuitian Avatar asked Aug 28 '12 02:08

qiushuitian


People also ask

What does getopt do in Bash?

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.

What is getopt for?

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.

Should I use getopt or getopts?

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.


2 Answers

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.

like image 133
Denis Rouzaud Avatar answered Oct 01 '22 09:10

Denis Rouzaud


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

like image 28
sMyles Avatar answered Oct 01 '22 09:10

sMyles