如何检查参数是否已提供给 bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8968752/
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
How to check that a parameter was supplied to a bash script
提问by node ninja
I just want to check if one parameter was supplied in my bash script or not.
我只想检查我的 bash 脚本中是否提供了一个参数。
I found this, but all the solutions seem to be unnecessarily complicated.
我发现了这个,但所有的解决方案似乎都不必要地复杂。
What's a simple solution to this simple problem that would make sense to a beginner?
对于初学者来说,这个简单问题的简单解决方案是什么?
回答by Adam Zalcman
Use $#
which is equal to the number of arguments supplied, e.g.:
使用$#
等于提供的参数数量,例如:
if [ "$#" -ne 1 ]
then
echo "Usage: ..."
exit 1
fi
Word of caution: Note that inside a function this will equal the number of arguments supplied to the function rather than the script.
注意事项:请注意,在函数内部,这将等于提供给函数而不是脚本的参数数量。
EDIT: As pointed out by SiegeXin bash you can also use arithmetic expressions in (( ... ))
. This can be used like this:
编辑:正如SiegeX在 bash 中指出的,您也可以在(( ... ))
. 这可以像这样使用:
if (( $# != 1 ))
then
echo "Usage: ..."
exit 1
fi
回答by h7r
The accepted solution checks whether parameters were setby testing against the count of parameters given. If this is not the desired check, that is, if you want to check instead whether a specific parameter was set, the following would do it:
接受的解决方案通过针对给定参数的计数进行测试来检查是否设置了参数。如果这不是所需的检查,也就是说,如果您想检查是否设置了特定参数,则执行以下操作:
for i in "$@" ; do
if [[ $i == "check parameter" ]] ; then
echo "Is set!"
break
fi
done
Or, more compactly:
或者,更简洁:
for i in "$@" ; do [[ $i == "check argument" ]] && echo "Is set!" && break ; done
回答by jaypal singh
if (( "$#" != 1 ))
then
echo "Usage Info:…"
exit 1
fi