getopts的无参数提供 [英] getopts no argument provided

查看:615
本文介绍了getopts的无参数提供的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查是否有没有必需的参数前提?我发现:在开关外壳选项应该用于此目的是足够的,但它永远不会进入这种情况下(codeblock伪)。不要紧,我是否把冒号案开头或其他地方。

how to check whether there was no required argument provided? I found that ":" option in switch case should be sufficient for this purpose, but it never enters that case (codeblock). It doesn't matter whether I put "colon-case" at the beginning or elsewhere.

我的code:

while getopts :a:b: OPTION;
do
     case "$OPTION" in
         a)
             var1=$OPTARG
             ;;
         b)
             var2=$OPTARG
             ;;
         ?)
             exitScript "`echo "Invalid option $OPTARG"`" "5"
             ;;
         :)
             exitScript "`echo "Option -$OPTARG requires an argument."`" "5"
             ;;
         *)
             exitScript "`echo "Option $OPTARG unrecognized."`" "5"
             ;;
     esac
done

THX在前进。

THX in advance.

推荐答案

您必须逃离。接下来就可以(部分)的作品。

You must escape the ?. The next can (partially) works.

err() { 1>&2 echo "$0: error $@"; return 1; }
while getopts ":a:b:" opt;
do
        case $opt in
                a) aarg="$OPTARG" ;;
                b) barg="$OPTARG" ;;
                :) err "Option -$OPTARG requires an argument." || exit 1 ;;
                \?) err "Invalid option: -$OPTARG" || exit 1 ;;
        esac
done

shift $((OPTIND-1))
echo "arg for a :$aarg:"
echo "arg for b :$barg:"
echo "unused parameters:$@:"

部分,因为当会调用上面的脚本

Partially because when will call the above script as

$ bash script -a a_arg -b b_arg extra

将工作像您期望的,

will works as you expect,

arg for a :a_arg:
arg for b :b_arg:
unused parameters:extra:

但是,当你称呼其为

But when you will call it as

bash script -a -b b_arg

将打印

arg for a :-b:
arg for b ::
unused parameters:b_arg:

什么不是,你想要什么。

what is not, what you want.

和UUOE。 (Useles使用echo)。

And UUOE. (Useles use of echo).

这篇关于getopts的无参数提供的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆