getopts no argument provided

拈花ヽ惹草 提交于 2020-01-04 14:08:10

问题


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.

my 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 in advance.


回答1:


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

will prints

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

what is not, what you want.

And UUOE. (Useles use of echo).




回答2:


?) in the case block should be written as "?").



来源:https://stackoverflow.com/questions/16454460/getopts-no-argument-provided

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!