- Learning Linux Shell Scripting
- Ganesh Naik
- 316字
- 2021-06-25 22:02:56
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 Four
All arguments passed are as follows:
One Two Three Four
Shift by one position.
Here, the value of the positional parameter $1 after shift is:
Two
Shift by two positions.
The value of the positional parameter $1 after two shifts:
Four
We can see that, initially, $1 was One. After the shift, $1 will be pointing to Two. Once the shift has been done, the value in position 1 is always destroyed and is inaccessible.
Create script shift_02.sh, as follows:
#!/bin/bash echo '$#: ' $# echo '$@: ' $@ echo '$*: ' $* echo echo '$1 $2 $9 $10 are: ' $1 $2 $9 $10 echo shift echo '$#: ' $# echo '$@: ' $@ echo '$*: ' $* echo echo '$1 $2 $9 are: ' $1 $2 $9 shift 2 echo '$#: ' $# echo '$@: ' $@ echo '$*: ' $* echo echo '$1 $2 $9 are: ' $1 $2 $9 echo '${10}: ' ${10}
From this script's execution, the following output is shown:
- Initially, $1 to $13 were numerical values 1 to 13, respectively.
- When we called the command shift, it then$1 shifted to number 2, and all $numbers were shifted accordingly.
- When we called the command shift 2, then $1 shifted to number 4 and all $numbers were shifted accordingly.