I did see the post Explain shell command shift. As i am unable to comment there i would like to know the use of Shift command. Does it mean that the parameters passed to the script will be empty after the point where shift is used? what would be the advantage of the command
It may result in an empty arg list, or it may not. It depends on how many args there were to start with, and how many relevant args
getopts found (and set in $OPTIND). getopts ignores all arguments not beginning with
-- tells getopts to stop processing any subsequent args as options (e.g.
rm -f -- -filenamebeginningwith-.txt).
e.g. if you have 5 args
-x -y -z file1 file2, then
shift 3 will get rid of the first three args, leaving just
The reason for the command
shift $((OPTIND -1)) is to "skip" the options that have been parsed by
getopts and to leave the file type arguments available for further processing.
$OPTIND is a shell variable managed by the
getopts builtin command of the shell. When the shell starts,
$OPTIND equals 1 and is incremented every time a
getopts call discoveres options or option arguments.
shiftremoves an arbitrary amount of arguments from the beginning of the current list of arguments.
shift 3will irrecoverable remove the 3 first arguments from the list of arguments from the shell.
Basically the "shift" command allows you to "go through" the arguments passed to a script or a function.
The main use is to access $0 in a loop, while "shifting" until you get no more arguments left.
The exact use of shift $(($OPTIND-1)) is to skip the options parsed and standardized by getopts (i.e. -uvh will become -u -v -h), so by doing so, you will have your first "non-option" argument in the $0 position of the argument array.