官术网_书友最值得收藏!

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:

  1. Initially, $1 to $13 were numerical values 1 to 13, respectively.
  2. When we called the command shift, it then$1 shifted to number 2, and all $numbers were shifted accordingly.
  3. When we called the command shift 2, then $1 shifted to number 4 and all $numbers were shifted accordingly.
主站蜘蛛池模板: 霍城县| 镇宁| 图木舒克市| 射阳县| 讷河市| 苏尼特右旗| 双辽市| 习水县| 泰来县| 荆门市| 绥德县| 甘孜| 葫芦岛市| 保靖县| 天水市| 涿鹿县| 平湖市| 康马县| 抚顺县| 建德市| 海口市| 都匀市| 宁津县| 武清区| 乌恰县| 高雄县| 尖扎县| 加查县| 纳雍县| 化州市| 丹东市| 新河县| 舟曲县| 松滋市| 巴彦淖尔市| 大田县| 新津县| 蓝山县| 县级市| 宁波市| 惠东县|