bash - 在 bash 中测试命令行参数

标签 bash command-line

我正在测试我的脚本的第一个参数是否是 --foo

if [ $# > 1 ]
then
    if [[ "$1" = "--foo" ]]
    then
        echo "foo is set"
        foo = 1
    fi
fi

if [[ -n "$foo"]]
then
    #dosomething
fi

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

最佳答案

如果您想支持长选项,您应该使用外部 getopt 实用程序。如果您只需要支持短选项,最好使用 Bash 内置的 getopts

下面是一个使用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))

并不是说您的第一个测试将始终显示 true 结果,并且会在当前目录中创建一个名为“1”的文件。您应该使用(按优先顺序):

if (( $# > 1 ))

if [[ $# -gt 1 ]]

if [ $# -gt 1 ]

此外,对于赋值,等号两边不能有空格:

foo=1

关于bash - 在 bash 中测试命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5302440/

相关文章:

linux - 如何获取 Bash 中的总物理内存以将其分配给变量?

macos - Bash 别名给出的结果与仅运行命令不同

windows - 将输出中的特定字段保存到 Windows CMD 上的变量中

go - 在 GoLang 中定义独立的标志集

command-line - 如何使用 applescript 获取 iTunes 轨道的播放时间?

linux - 目录内容更改时增加文件名的 shell 脚本 (centos)

xml - 使用 xmlstarlet 编辑 XML 中的值

command-line - 安装oAuth PECL错误: Cannot install, php_dir for channel "pecl.php.net"is not writeable by current user

linux - 我可以在 Linux 上用一条命令做多件事吗?

arrays - 如何将数组传递给函数并且对数组的更新反射(reflect)在函数之外