I'm trying to get a script to:
* set a variable with
-q
option
* show help for -h
option, and
* fail for other options -*
, but allow positional arguments
Here is the getopts
snippet I'm using:
while getopts qh opt; do
case "${opt}" in
q)
quiet="true"
;;
h)
usage
exit 1
;;
\?)
echo "unrecognized option -- ${OPTARG}"
exit 1
;;
esac
shift
done
echo "unparsed: $*"
This seems pretty straightforward. However it only works if I provide a single argument (a.sh -q
or a.sh -h
do what's expected).
However, it does not do anything if I provide both arguments, or provide an unrecognized argument as at $2:
$ ./a.sh -b
unrecognized option -- b
$ ./a.sh -q -b
unparsed: -b
$ ./a.sh -h -k
this is my help message
unparsed: -k
Any ideas why the second argument ($2) is not handled in the getopts loop?
Asked by ahmet alp balkan
(741 rep)
Oct 8, 2017, 05:11 AM
Last activity: Dec 18, 2023, 09:25 AM
Last activity: Dec 18, 2023, 09:25 AM