shift
Shifts positional parameters left
TLDR
Remove the first positional parameter
Remove the first n positional parameters
SYNOPSIS
shift [n]
PARAMETERS
n
An optional integer specifying the number of positions to shift the parameters. If n is omitted, it defaults to 1. n must be a non-negative integer less than or equal to the current number of positional parameters ($#).
DESCRIPTION
shift is a powerful shell built-in command used within shell scripts or functions to manipulate positional parameters (like $1, $2, $3, etc.). When shift is called without arguments, it renames the positional parameters: $2 becomes $1, $3 becomes $2, and so on. The original $1 is discarded. This is particularly useful for iterating through a list of command-line arguments, especially when some arguments might be options that need to be processed before the remaining arguments. For instance, after processing an option and its value (e.g., -o value), shift can be used twice to remove both from the argument list, bringing the next argument to $1. The special parameter $#, which holds the number of positional parameters, is decremented by the shift amount. If shift is called with an argument n, it shifts the parameters n times. For example, shift 2 would discard $1 and $2, move $3 to $1, $4 to $2, and so forth. If n is greater than $#, it's an error. This command is fundamental for writing robust scripts that parse various types of command-line input.
CAVEATS
shift is a shell built-in command, not an external executable. This means it operates directly within the shell's memory space and doesn't require a separate process to run.
It directly modifies the shell's positional parameters of the current script or function, affecting subsequent access to $1, $2, etc.
Shifting past the available parameters (n > $#) will result in an error and the command's exit status will be non-zero.
The original values of the shifted-out parameters (e.g., $1 when shift is called) are lost and cannot be retrieved.
COMMON USAGE PATTERN
A common pattern for processing all arguments in a script or function is a while loop:
while [ "$#" -gt 0 ]; do
# Process $1
shift
done
This loop continues as long as there are arguments remaining. After each iteration, shift moves the next argument into $1, effectively consuming the current $1.
HISTORY
The shift command has been a fundamental feature of Unix shells since their early days, including the Bourne shell (sh) and later shells like csh, ksh, bash, and zsh. Its core functionality of manipulating positional parameters for command-line argument processing has remained consistent due to its essential role in scripting. Its simplicity and effectiveness have ensured its continued presence as a basic building block for shell programming.