英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论