在 bash 中测试命令行参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5302440/
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
testing for command line args in bash
提问by MK.
I am testing to see if the first argument to my script is --foo
我正在测试我的脚本的第一个参数是否是 --foo
if [ $# > 1 ]
then
if [[ "" = "--foo" ]]
then
echo "foo is set"
foo = 1
fi
fi
if [[ -n "$foo"]]
then
#dosomething
fi
Can someone pleaset tell me what is the bash way of testing if --foo
is present as one of the arguments, not necessarily the first one?
有人可以告诉我 bash 的测试方式是什么,如果--foo
作为参数之一出现,不一定是第一个?
回答by Paused until further notice.
You should use the external getopt
utility if you want to support long options. If you only need to support short options, it's better to use the the Bash builtin getopts
.
getopt
如果您想支持长选项,您应该使用外部实用程序。如果您只需要支持短选项,最好使用 Bash 内置getopts
.
Here is an example of using getopts
(getopt
is not too much different):
下面是一个使用getopts
(getopt
并没有太大不同)的例子:
options=':q:nd:h'
while getopts $options option
do
case $option in
q ) queue=$OPTARG;;
n ) execute=$FALSE; ret=$DRYRUN;; # do dry run
d ) setdate=$OPTARG; echo "Not yet implemented.";;
h ) error $EXIT $DRYRUN;;
\? ) if (( (err & ERROPTS) != ERROPTS ))
then
error $NOEXIT $ERROPTS "Unknown option."
fi;;
* ) error $NOEXIT $ERROARG "Missing option argument.";;
esac
done
shift $(($OPTIND - 1))
Not that your first test will always show a true
result and will create a file called "1" in the current directory. You should use (in order of preference):
并不是说您的第一个测试将始终显示true
结果并在当前目录中创建一个名为“1”的文件。您应该使用(按优先顺序):
if (( $# > 1 ))
or
或者
if [[ $# -gt 1 ]]
or
或者
if [ $# -gt 1 ]
Also, for an assignment, you can't have spaces around the equal sign:
此外,对于作业,等号周围不能有空格:
foo=1
回答by Peter Wagener
As Dennis noted, getopt
and getopts
are the standard ways for parsing command line arguments. For an alternative way, you could use the $@special variable, which expands to allof the command line arguments. So, you could test for it using the wildcardin your test:
正如 Dennis 所指出的,getopt
和getopts
是解析命令行参数的标准方法。对于另一种方法,您可以使用$@特殊变量,它扩展到所有命令行参数。因此,您可以在测试中使用通配符对其进行测试:
#!/usr/bin/env bash
if [[ $@ == *foo* ]]
then
echo "You found foo"
fi
That said, you'll be better off if you figure out getopt sooner rather than later.
就是说,如果您尽早找出 getopt,您会过得更好。