Skip to content
Tutorials Center
My learning

Topics

Linux Command Reference ยท Shell Builtins

Linux shift command

Reference for the Bash shift builtin: drop leading positional parameters, process arguments in loops, shift by N, and handle the out-of-range error.

shift removes parameters from the front of the positional list. After shift, what was $2 becomes $1, $3 becomes $2, and so on; $# decreases by one, and the old $1 is gone. The shell does this to the parameters of the script or of the current function.

It is the standard way to consume arguments one at a time (while [ $# -gt 0 ]; do ...; shift; done), to peel off a subcommand such as git commit, or to remove options once getopts is done.

Terminal
shift       # drop $1
shift 2     # drop $1 and $2

Try it

Bash Consuming arguments one by one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Bash Subcommands and options with values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Syntax

Terminal
shift [N]
Name Description
N How many parameters to remove. Default 1. Must be a non-negative integer.

Returns: 0 on success. If N is larger than $#, the status is non-zero (1) and nothing is removed. shift 0 does nothing and succeeds.

Errors: a negative or non-numeric N is an error. In a non-interactive POSIX-mode shell an out-of-range shift can terminate the script.

Usage notes

  • Check $# first. shift 2 on a single remaining argument fails and leaves it in place. Test [ $# -ge 2 ] before consuming an option's value.
  • Options with values. --name value needs shift 2; --name=value needs one shift. Parse both, as the second example shows.
  • After getopts. Run shift $((OPTIND - 1)) to remove the options and keep the operands.
  • Functions have their own list. Inside a function, shift changes the function's parameters and does not touch the caller's.
  • $0 never moves. Only $1 and higher are affected.
  • Arrays offer more control. args=("$@") copies the list; you can then slice it with "${args[@]:1}" without losing the original.
  • Combine with $@. Use "$@" to forward what is left to another command: exec git "$@".
  • Sets from set --. set -- new list replaces all positional parameters at once, a convenient way to restart.