如何防止将参数传递给不带getopt的参数?

时间:2016-05-18 11:18:25

标签: linux bash parsing parameters getopt

例如,考虑这个脚本,

#!/bin/sh

OPTS=`getopt -o ahb:c: --long help,name:,email: -- "$@"`
#echo "$OPTS"
eval set -- "$OPTS"

usage () {
    echo "type -h for help"
}


while true; do
    case "$1" in
        -a) echo "a is a short option that do not take parameters"; shift ;;
        -b) echo "b is a short option that requires one parameter and you specified $2"; shift 2;;
        -c) echo "c is a short option that requires one parameter and you specified $2"; shift 2;;
        --name) echo "your name is $2"; shift 2;;
        --email) echo "your email is $2"; shift 2;;
        -h | --help) echo "Google search yourself !"; shift 1;;
        --) usage ; shift; break ;;
        *) echo "hello"; break ;;

    esac
done

因此,如果将脚本调用为sh myscript.sh -a hello,则应该抛出一个错误,告诉-a不接受任何参数。

有办法吗?

1 个答案:

答案 0 :(得分:1)

你遇到的问题是因为你不想要一个“第二”参数但是它实际上是第三个参数!

如果在-a之后不需要任何参数,则需要检查是否存在$ 3。 ($ 2将是' - ')

以下是在-a:

之后提供内容时会输出错误的固定代码
#!/bin/sh

OPTS=`getopt -o ahb:c: --long help,name:,email: -- "$@"`
#echo "$OPTS"
eval set -- "$OPTS"

usage () {
    echo "type -h for help"
}


while true; do
    case "$1" in
        -a) if [ ! -z "$3" ] ; then 
#Check if there is something after -a
                echo "a is a short option that do not take parameters";
else
         echo "Whatever..";
fi
 shift ;;
        -b) echo "b is a short option that requires one parameter and you specified $2"; shift 2;;
        -c) echo "c is a short option that requires one parameter and you specified $2"; shift 2;;
        --name) echo "your name is $2"; shift 2;;
        --email) echo "your email is $2"; shift 2;;
        -h | --help) echo "Google search yourself !"; shift 2;;
        --) usage ; shift; break ;;
        *) echo "hello"; break ;;

    esac
done

我希望这就是你要找的东西:)