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.
shift # drop $1 shift 2 # drop $1 and $2
Try it
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.
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
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 2on a single remaining argument fails and leaves it in place. Test[ $# -ge 2 ]before consuming an option's value. - Options with values.
--name valueneedsshift 2;--name=valueneeds one shift. Parse both, as the second example shows. - After
getopts. Runshift $((OPTIND - 1))to remove the options and keep the operands. - Functions have their own list. Inside a function,
shiftchanges the function's parameters and does not touch the caller's. $0never moves. Only$1and 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 listreplaces all positional parameters at once, a convenient way to restart.
Related
getopts,set,read, Special parameters, Functions- Lessons: Script arguments, Functions, Loops