What is the reason for using shift $ ((OPTIND-1)) after getopts?
My understanding is that shift moves the cli array args n space to the left, and the default n is 1. This means that I can assign values โโto the array to existing variables using the $ 1 shift inside the while loop. I don't quite understand why it is used in this context below. The input arguments have already been assigned to values โโand removing the $ ((OPTIND-1)) offset does not change this fact. Source: http://linux.die.net/man/3/optind
while getopts ":h:a:fc" opt; do
case $opt in
h)
print_help
exit 0
;;
a)
aaaa=${OPTARG}
;;
f)
force=1
;;
c)
CLEAN=1
;;
\?)
echoerr "Invalid option -$OPTARG"
print_help
exit 1
;;
esac
done
shift $((OPTIND-1))
source to share
Offset removes the parameters processed by the loop getopts
from the parameter list, so that the rest of the script can process the rest of the command line (if any) with $ 1 ... in the usual way, disregarding the number of options processed getopts
.
Consider a hypothetical script using
frobble [-f] [-c] [-a hostname] filename ...
The getopts
above loop takes care of parsing -f
, -c
and -a
if present, it does not remove them from the argument list. This means that in order to get the filename argument, you need to figure out how many options were processed and continue processing from there. Conveniently, getopts
it tells you the index of the first raw argument: variable OPTIND
.
And instead of messing up offsets and stuff, you can simply discard the processed parameters by renumbering the rest of the arguments so that your filename is always there $1
.
This is what it does shift $((OPTIND-1))
.
source to share