Session and utilities

The shift command

Drops the first script argument and moves the rest left: $2 becomes $1.

Copy-ready examples

$ set -- a b c && shift && echo $1drops the first argument and shows the new one.

Example output

b
$ set -- a b c d && shift 2 && echo $*drops two arguments at once.

Example output

c d
$ printf 'echo "inicio: $1 $2"\nshift\necho "tras shift: $1"\n' > s.sh && bash s.sh uno dosa script that uses shift and receives two arguments.

Example output

inicio: uno dos
tras shift: dos

You can try them in the browser terminal: it does not touch your computer.

Common errors

MessageCauseFix
bash: shift: -1: shift count out of rangeYou passed a negative number. n must be 0 or greater.Use a natural number, or none: shift is the same as shift 1.
bash: shift: abc: numeric argument requiredThe argument to shift is not a number.Pass an integer, for example shift 2.

Typical mistakes

  • After shift, $# goes down: with two arguments and one shift, one is left.
  • With an n greater than $#, nothing changes and it returns a non-zero code, with no error message.
  • Inside a function, shift affects the arguments of that function, not those of the script.

Differences from similar commands

  • set --: replaces all positional parameters at once. shift only removes the first ones and moves the rest.
  • getopts: reads options by letter. A script with options often uses getopts and then shift to remove the ones already read.
  • unset: removes a variable. shift does not remove a variable: it moves the parameters, and the last ones are left without a value.

Related commands

FAQ

What does shift do without a number?

The same as shift 1: it removes the first argument.

How do I go through all the arguments?

With a loop: while [ $# -gt 0 ]; do ...; shift; done. You process $1 and then remove it; the loop ends when $# reaches 0.

What is the difference with $@?

$@ is the full argument list and $# its count. shift changes that list and lowers $#.

Learn to actually use it

The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.

Start the free course