I want to use getopts but the default case doesn't work.
The code that I tried is:
while getopts "sdp" arg; do
case "$arg" in
s)
echo "1"
;;
p)
echo "2"
;;
d)
echo "3"
;;
*)
echo "default"
;;
esac
when I run the process: ./myTask
I didn't receive any output
It's working as intended.
The default case is not to handle the case where you don't have arguments, but the case where you supply invalid arguments:
$ ./myTest -X
./myTest: illegal option -- X
default
Normally you would write a usage message in this case.
That's the default of the case
statement, but it means something specific in the context of getopts
: That you have an option defined but no clause to handle it.
If you run ./myTask -z
, for example, you will see the output of "default" as @that_other_guy states in another answer here.
If you want to output something that indicates that no option was supplied:
Then after the while getopts
block but before the shift $(($OPTIND - 1))
line, do this (with whatever processing you want inside the if
block:
if ((OPTIND == 1))
then
echo "No options specified"
fi
Note that this does not indicate that no arguments were specified (eg ./myTask
as in your question). To do something with that, add this after the shift
line:
if (($# == 0))
then
echo "No positional arguments specified"
fi
Please see a reference implementation of a getopts
function in my answer here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.