Understanding shift

Using shift, we can change the parameter to which $1 and $2 are pointing to the next variable.

Create script shift_01.sh, as follows:

#!/bin/bash 
echo "All Arguments Passed are as follow : " 
echo $* 
echo "Shift By one Position :" 
shift 
echo "Value of Positional Parameter $ 1 after shift :" 
echo $1 
echo "Shift by Two Positions :" 
shift 2 
echo "Value of Positional Parameter $ 1 After two Shifts :" 
echo $1 

Execute the following command:

$ chmod +x shift_01.sh$ ./shift_01.sh One Two Three Four

The output is as follows:

[student@localhost ~]$ ./shift_01.sh One Two Three FourAll arguments passed are as follows:One Two Three FourShift by one position.Here, the value of the positional parameter $1 after shift is:TwoShift by two ...

Get Learning Linux Shell Scripting - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.