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

后端 未结 3 799
不思量自难忘°
不思量自难忘° 2021-02-07 01:06

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

相关标签:
3条回答
  • 2021-02-07 01:25

    It's generally a better idea to use getopts instead, and stick with short options. You can see getopts in action in this StackOverflow Q&A. Short options are more standard throughout OSX command line tools, and consistency is a good thing.

    Also, getopts is built in to bash, so it's definitely available in OSX, as well as every other platform that can run bash.

    Note that there is a getopt is also available in OSX. From Terminal, type man getopt to see its documentation. It doesn't support long options. This is a good reason not to use long options when you're writing tools to run on OSX.

    If you want to do this anyway, you can install getopt from macports. Alternately, if you want better portability, you can roll your own long argument handling.

    Post some code, and we'll help debug it.

    0 讨论(0)
  • 2021-02-07 01:35

    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.

    0 讨论(0)
  • 2021-02-07 01:37

    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

    0 讨论(0)
提交回复
热议问题