getopt 在 MacOS 下对短选项的使用不如预期。

huangapple go评论70阅读模式
英文:

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

问题

我有以下命令:command.sh bar -b=FOO

我试图使用以下方式解析它:getopt "m::b::" "$@"

在Linux下,结果是:-b =FOO -- command.sh bar

在MacOS下,结果是:-- command.sh bar -b=FOO。因此,它根本没有被解析。我尝试过-bFOO-b FOO,但结果都一样,它没有被解析。

如何修复这个问题?我需要一个跨平台的bash解决方案,可以在Mac和Linux上都运行。

英文:

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.

答案1

得分: 5

getopt 是一个外部实用程序,与版本相关,因此您需要在Mac上的版本与您在Linux上使用的版本匹配。相反,使用 getopts,它是内置的。它是可移植的,并且在任何POSIX shell中可以立即使用。

示例:

while getopts "m::b::" opt; do
  case ${opt} in
    m) # 执行 'm' 操作
      echo M
      ;;
    b) # 执行 'b' 操作
      echo B
      ;;
  esac
done
英文:

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

huangapple
  • 本文由 发表于 2023年3月7日 13:48:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75658426.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定