如何验证shell参数?

时间:2014-07-31 17:09:20

标签: shell validation command-line-arguments

我正在尝试编写一个简单的sh脚本,必须使用2个参数调用:

sh myscript.sh --user "some user" --fizz "buzz"

myscript.sh的顶部,我有:

#!/bin/sh
# VALIDATION
# 1. Make sure there are 5 positional arguments (that $4 exists).
die () {
    echo >&2 "$@"
    exit 1
}

[ "$#" -eq 5 ] || die "5 arguments required, $# provided"

# 2. Make sure $1 is "-u" or "--user".
# 3. Make sure $3 is "-f" or "--fizz".

如果验证失败,我想打印一条简单的用法消息,然后退出脚本。

认为我有#1正确(检查位置参数#),但不知道如何实现#2和#3。想法?

2 个答案:

答案 0 :(得分:1)

# 2. Make sure $1 is "-u" or "--user".

if ! [ "$1" = -u -o "$1" = --user ]; then
    # Test failed. Send a message perhaps.
    exit 1
fi

# 3. Make sure $3 is "-f" or "--fizz".

if ! [ "$3" = -f -o "$3" = --fizz ]; then
    # Test failed. Send a message perhaps.
    exit 1
fi

用于测试两个可能的值的变量的其他形式:

[ ! "$var" = value1 -a ! "$var" = value2 ]
[ ! "$var" = value1 ] && [ ! "$var" = value2 ]
! [ "$var" = value1 && ! [ "$var" = value2 ]

对于Bash和类似语法的shell:

! [[ $var = value1 || $var = value2 ]]
[[ ! $var = value1 || ! $var = value2 ]]

除了使用if块的否定条件外,您还可以使用||

获得积极的条件
true_condition || {
    # Failed. Send a message perhaps.
    exit 1
}

true_condition || exit 1

另一方面,&&当然会适用于否定的条件。

使用案例陈述:

case "$var" in
value1|value2)
    # Valid.
    ;;
*)
    # Failed.
    exit 1
    ;;
esac

答案 1 :(得分:0)

手动:

if [ -z "$1" ];then
fi

if [ -z "$2" ];then
fi

if [ -z "$3" ];then
fi
...

或检查getopt

while getopts "uf" OPTION
do
 case $OPTION in
     u)
         echo "-u"
         ;;
     f)
         echo "-f"
         ;;
 esac
done