使用 getopt 在 Bash 中解析长样式参数时遇到问题
Trouble Parsing Long Style Arguments in Bash using getopt
我的这个脚本似乎没有识别除 --norecopy 之外的任何其他选项,甚至只有在指定为我的脚本的第二个参数时才识别。
有人可以指出我做错了什么吗?
#!/usr/bin/env bash
norecopy=false
noencrypt=false
nopackage=false
# read the option
OPTS=`getopt --long norecopy,noencrypt,nopackage -n 'build' -- "$@"`
eval set -- "$OPTS"
while true ; do
case "" in
--norecopy ) echo "found norecopy" ; norecopy=true ; shift ;;
--noencrypt ) echo "found noencrypt" ; noencrypt=true ; shift ;;
--nopackage ) echo "found nopackage" ; nopackage=true ; shift ;;
-- ) echo "Got here" ; shift ; break ;;
* ) echo "unsupported option!" ; break ;;
esac
done
exit 0
下面的代码有效!
#!/usr/bin/env bash
norecopy=false
noencrypt=false
nopackage=false
# read the option
OPTS=`getopt --long norecopy,noencrypt,nopackage -n 'build' - "$@"`
eval set -- "$OPTS"
while true ; do
case "" in
--norecopy ) echo "found norecopy" ; norecopy=true ; shift ;;
--noencrypt ) echo "found noencrypt" ; noencrypt=true ; shift ;;
--nopackage ) echo "found nopackage" ; nopackage=true ; shift ;;
-- ) echo "Got here" ; shift ; break ;;
* ) echo "unsupported option!" ; break ;;
esac
done
exit 0
我添加了 'set -x' 来调试问题。我看到 getopt 命令中的单个连字符(而不是两个连续的连字符)按预期打印输出。看下面两条命令:
$ getopt --long norecopy,noencrypt,nopackage -n build -- --norecopy --noencrypt --nopackage
--noencrypt --nopackage --
$ getopt --long norecopy,noencrypt,nopackage -n build - --norecopy --noencrypt --nopackage
--norecopy --noencrypt --nopackage --
我仍然不知道 getopt 这种行为背后的原因。论坛上有 getopt 源代码经验的人可能会提供帮助。但是,此更改应该会让您继续前进!
我的这个脚本似乎没有识别除 --norecopy 之外的任何其他选项,甚至只有在指定为我的脚本的第二个参数时才识别。
有人可以指出我做错了什么吗?
#!/usr/bin/env bash
norecopy=false
noencrypt=false
nopackage=false
# read the option
OPTS=`getopt --long norecopy,noencrypt,nopackage -n 'build' -- "$@"`
eval set -- "$OPTS"
while true ; do
case "" in
--norecopy ) echo "found norecopy" ; norecopy=true ; shift ;;
--noencrypt ) echo "found noencrypt" ; noencrypt=true ; shift ;;
--nopackage ) echo "found nopackage" ; nopackage=true ; shift ;;
-- ) echo "Got here" ; shift ; break ;;
* ) echo "unsupported option!" ; break ;;
esac
done
exit 0
下面的代码有效!
#!/usr/bin/env bash
norecopy=false
noencrypt=false
nopackage=false
# read the option
OPTS=`getopt --long norecopy,noencrypt,nopackage -n 'build' - "$@"`
eval set -- "$OPTS"
while true ; do
case "" in
--norecopy ) echo "found norecopy" ; norecopy=true ; shift ;;
--noencrypt ) echo "found noencrypt" ; noencrypt=true ; shift ;;
--nopackage ) echo "found nopackage" ; nopackage=true ; shift ;;
-- ) echo "Got here" ; shift ; break ;;
* ) echo "unsupported option!" ; break ;;
esac
done
exit 0
我添加了 'set -x' 来调试问题。我看到 getopt 命令中的单个连字符(而不是两个连续的连字符)按预期打印输出。看下面两条命令:
$ getopt --long norecopy,noencrypt,nopackage -n build -- --norecopy --noencrypt --nopackage
--noencrypt --nopackage --
$ getopt --long norecopy,noencrypt,nopackage -n build - --norecopy --noencrypt --nopackage
--norecopy --noencrypt --nopackage --
我仍然不知道 getopt 这种行为背后的原因。论坛上有 getopt 源代码经验的人可能会提供帮助。但是,此更改应该会让您继续前进!