问题
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