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

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.
主站蜘蛛池模板: 海兴县| 三原县| 卢湾区| 镇巴县| 烟台市| 高尔夫| 迭部县| 常德市| 临城县| 逊克县| 香港| 芮城县| 达孜县| 海南省| 翼城县| 东宁县| 札达县| 阿拉善右旗| 吉木乃县| 达孜县| 沿河| 淮南市| 衡山县| 拉萨市| 定州市| 阿拉善右旗| 唐河县| 安顺市| 科尔| 阿克苏市| 大同市| 鲜城| 黑龙江省| 莒南县| 化隆| 革吉县| 鱼台县| 乐昌市| 黄冈市| 新余市| 阿拉善左旗|