2

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.

4

2 回答 2

5

你必须逃避?. 下一个可以(部分)工作。

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:$@:"

部分原因是什么时候将上述脚本称为

$ bash script -a a_arg -b b_arg extra

将按您的预期工作,

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

但是当你把它称为

bash script -a -b b_arg

将打印

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

什么不是,你想要什么。

和UUOE。(使用回声)。

于 2013-05-09T04:57:44.137 回答
2

?)case块中应写为"?").

于 2013-05-09T04:47:11.307 回答