Shifting positional arguments after call to getopts

301 Views Asked by At

Getopts uses OPTIND to store the positional argument number. It is then a practice to shift the positional arguments in the following way.

  shift "$(( OPTIND - 1 ))"

For what purpose does one do that ?

1

There are 1 best solutions below

3
yinyu985 On

The purpose of shifting the positional arguments using shift "$(( OPTIND - 1 ))" after using getopts is to remove all the options and their corresponding arguments that have already been processed by getopts. This ensures that the remaining arguments are the non-option arguments that can be processed separately. OPTIND contains the index of the next argument to be processed by getopts, so subtracting 1 from it gives the number of options processed, which is the number of arguments to shift.