在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:17:05  来源:igfitidea点击:

testing for command line args in bash

bashcommand-line

提问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 --foois present as one of the arguments, not necessarily the first one?

有人可以告诉我 bash 的测试方式是什么,如果--foo作为参数之一出现,不一定是第一个?

回答by Paused until further notice.

You should use the external getoptutility 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(getoptis 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 trueresult 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, getoptand getoptsare 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 所指出的,getoptgetopts是解析命令行参数的标准方法。对于另一种方法,您可以使用$@特殊变量,它扩展到所有命令行参数。因此,您可以在测试中使用通配符对其进行测试:

#!/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,您会过得更好。