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
4 Answers
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 -
, and --
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 file1 file2
.
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.
Note that $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.
shift
removes an arbitrary amount of arguments from the beginning of the current list of arguments.
- Calling
shift 3
will 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.
A demonstration may illuminate:
$ set -- 1 2 3 4 5 6 # set the positional parameter $1, $2, ...
$ echo "$@" # print the positional params
1 2 3 4 5 6
$ shift 3
$ echo "$@"
4 5 6
Now, [ $1 -eq 4 ] && [ $2 -eq 5 ] && [ $3 -eq 6 ]