The shift command in bash

The shift command in Bash is used to shift the positional parameters to the left, discarding the value of $1 and moving the remaining arguments ($2, $3, and so on) to lower positions ($1, $2, and so on). It effectively shifts the values of the command-line arguments, allowing you to access and process them in a sequential manner.

The syntax of the shift command is simply:

shift [n]

The optional n argument specifies the number of positions to shift. If n is not provided, the default value is 1, which means shifting the positional parameters one position to the left.

Here’s an example to illustrate the usage of the shift command:


echo "Original arguments:"
echo "Argument 1: $1"
echo "Argument 2: $2"
echo "Argument 3: $3"

shift 2

echo "Shifted arguments:"
echo "Argument 1: $1"
echo "Argument 2: $2"

When you run this script with three command-line arguments (./ arg1 arg2 arg3), the output will be:

Original arguments:
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3
Shifted arguments:
Argument 1: arg3
Argument 2:

In this example, after the shift 2 command, the values of $1 and $2 are discarded, and the remaining arguments are shifted to lower positions. $3 becomes the new $1, and $2 becomes empty.

The shift command is useful when you need to process a variable number of command-line arguments in a loop or when you want to focus on a subset of the arguments. By shifting the positional parameters, you can iterate through the arguments or access specific arguments based on your script’s requirements.

Leave a Comment

Your email address will not be published. Required fields are marked *