bash 选项需要参数错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22383336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
option requires an argument error
提问by Daniel
I wrote a shell script to do something. Everything works fine! A part of my code is something like this, so that I can pass options and arguments to it:
我写了一个shell脚本来做某事。一切正常!我的代码的一部分是这样的,所以我可以向它传递选项和参数:
while getopts "a:b:c" opt
do
case $opt in
a) AA=$OPTARG ;;
b) BB=$OPTARG ;;
c) CC=$OPTARG ;;
esac
done
shift $(expr $OPTIND - 1)
But now I want to add an option, say d
and I don't want it to use any argument, as the code shows below, but it ends with an error, complaining option requires an argument error -- d
It seems that getopts can't do that.
但是现在我想添加一个选项,比如说d
我不希望它使用任何参数,如下代码所示,但它以错误结束,抱怨option requires an argument error -- d
似乎getopts无法做到这一点。
while getopts "a:b:c:d" opt
do
case $opt in
a) AA=$OPTARG ;;
b) BB=$OPTARG ;;
c) CC=$OPTARG ;;
d) DD="ON" ;;
esac
done
shift $(expr $OPTIND - 1)
What should I do then? What is the common practice if I want both option types, one can accept argument, while the other doesn't need argument?
那我该怎么办?如果我想要两种选项类型,一种可以接受参数,而另一种不需要参数,那么通常的做法是什么?
回答by l0b0
The :
in the getopts
specifier is nota separator. From man getopts
:
将:
在getopts
符是不是一个分隔符。来自man getopts
:
if a character is followed by a colon, the option is expected to have an argument, which should be separated from it by white space.
如果一个字符后跟一个冒号,则该选项应该有一个参数,应该用空格与其分隔。
So if you want an option which doesn't take an argument, simply add the character. If you want it to take an argument, add the character followed by :
.
因此,如果您想要一个不带参数的选项,只需添加字符即可。如果您希望它接受一个参数,请添加后跟:
.
回答by that other guy
This would have happened if you had a colon after the d
in "a:b:c:d"
.
如果d
in后面有一个冒号,就会发生这种情况"a:b:c:d"
。
You don't have that in your code sample, and it accepts -d
with no arguments just fine.
你的代码示例中-d
没有它,它接受没有参数就好了。
Perhaps you took it off when writing your test case? The tag wikistep 2 for posting says to "Test your example. Make sure it runs and still shows the problem. Do not brush this off."
也许您在编写测试用例时取消了它?用于发布的标签 wiki第 2 步说“测试您的示例。确保它运行并仍然显示问题。不要忽略它。”