在bash中测试命令行参数

时间:2011-03-14 17:59:07

标签: 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方式是什么,不一定是第一个?

2 个答案:

答案 0 :(得分:34)

如果要支持长选项,则应使用外部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

答案 1 :(得分:9)

正如Dennis所说,getoptgetopts是解析命令行参数的标准方法。换句话说,您可以使用 $ @ 特殊变量,该变量扩展为命令行参数的全部。因此,您可以使用测试中的通配符来测试它:

#!/usr/bin/env bash

if [[ $@ == *foo* ]]
then
    echo "You found foo"
fi

那就是说,如果你早点发现getopt,你会好过的。

相关问题