I want to understand how OPTIND
works by getopts
. If I want to skip the first few positional arguments, how should I set up OPTIND
exactly ?
And because OPTIND is not reset automatically, I need to know how exactly to manually reset between multiple calls to getopts.
Because on the first call I get the error being reported
gopi -z
/usr/local/bin/bash: option requires an argument -- z
But the second call, the error is not reported
gopi -z
This is the function
gopi ()
{
local parg=""
while (( $# > 0 )); do
parg="$1"
case $parg in
("-s"|"--silent") opstring=":n:z:" ;;
(*) break ;;
esac # case ends here
shift 1
done
while getopts "$opstring" opname; do
case ${opname} in
("n") dothis ;;
("z") dothat ;;
(?)
## Invalid Option Found
echo "Invalid option: -$OPTARG" 1>&2
exit 1
;;
(:)
## Required option argument not found
echo "Option -$OPTARG requires an argument" 1>&2
exit 1
;;
esac
done
}