Basic Linux Tutorial
Computer Tutorial

The shift Command



The shift Command

The shift command is used to move the command line arguments one position left. The first argument is lost when you use the shift command. Shifting command line arguments is useful when you perform a similar action to all arguments, one-by-one, without changing the variable name. The shift command throws away the left-most variable (argument number 1) and reassigns values to the remaining variables. The value in $2 moves to $1, the value in $3 moves to $2, and so on.
Syntax :
shift   [n]

#!/usr/bin/sh
echo   " Total number of command line arguments is: $# "
echo   " These arguments are: $* "
echo   " The first argument is: $1 "
shift
echo   " New first argument after shift: $1 "
shift
echo   " First argument after another shift: $1 "
$

When we execute the program with three arguments red, green, and blue. We can see from the result that after every shift, a new value is assigned to $1. This value is the variable that is just on the right side of $1 (i.e., $2) The result is as shown below :


$ ./script red green blue
Total number of command line arguments is: 3
These arguments are: red green blue
The first argument is: red New first argument after shift: green First argument after another shift: blue $

The shift command is useful for:
• accessing positional parameters in groups, such as a series of x and y coordinates
• discarding command options from a command line, assuming that the options precede the arguments