Search code examples
bashmacosgetopt

getopt doesn't work as expected under MacOS with short options


I have the following command: command.sh bar -b=FOO

I'm trying to parse it with the following: getopt "m::b::" "$@"

Under Linux, the result is: -b =FOO -- command.sh bar

Under MacOS, the result is: -- command.sh bar -b=FOO. So it is not parsed at all. I tried -bFOO and -b FOO but with the same result, it was not parsed.

How to fix that? I need a cross-platform bash solution that will work both on Mac and Linux.


Solution

  • getopt is an external utility & version specific, so you need to match the version on Mac with the one you are used to on Linux.
    Rather, use getopts which is a builtin. It's portable & works in any POSIX shell right out-of-the-box.

    Example:

    while getopts "m::b::" opt; do
      case ${opt} in
        m) # do 'm' thing
          echo M
          ;;
        b) # do 'b' thing
          echo B
          ;;
      esac
    done