The shift builtin promotes each command line argument. The first argument (which was $1) is discarded. The second argument (which was $2) becomes the first argument (now $1), the third becomes the second, and so on. Because no "unshift" command exists, you cannot bring back arguments that have been discarded. An optional argument to shift specifies the number of positions to shift (and the number of arguments to discard); the default is 1.
The following demo_shift script is called with three arguments. Double quotation marks around the arguments to echo preserve the spacing of the output. The program displays the arguments and shifts them repeatedly until there are no more arguments left to shift:
$ cat demo_shift echo "arg1= $1 shift echo "arg1= $1 shift echo "arg1= $1 shift echo "arg1= $1 shift arg2= $2 arg2= $2 arg2= $2 arg2= $2
arg3= $3" arg3= $3" arg3= $3" arg3= $3"
$ demo_shift alice helen jenny arg1= alice arg2= helen arg3= jenny arg1= helen arg2= jenny arg3= arg1= jenny arg2= arg3= arg1= arg2= arg3=
Repeatedly using shift is a convenient way to loop over all the command line arguments in shell scripts that expect an arbitrary number of arguments. See page 401 for a shell script that uses shift.
Was this article helpful?