16.2.3 移动位置参数
在Shell中使用shift命令移动位置参数,第11章中曾简单讲到了在不加任何参数的情况下,shift命令可让位置参数左移一位,示例如下:
- [root@localhost ~]# cat shift_03.sh
#!/bin/bash
until [ $# -eq 0 ]
do
#
打印当前的第一个参数$1
,和参数的总个数$#
echo "Now \$1 is: $1, total parameter is:$#"
shift #
移动位置参数
done
#
运行结果
[root@localhost ~]# bash shift_03.sh a b c d
Now $1 is: a, total parameter is:4
Now $1 is: b, total parameter is:3
Now $1 is: c, total parameter is:2
Now $1 is: d, total parameter is:1
可以在shift命令后跟上向左移动的位数,比如说shift 2就是将位置参数整体向左移动两位。将上面的脚本修改一下后,运行结果如下:
#
如果将shift_03.sh
脚本中的shift
改为shift 2
,则位置参数将会每次移动两位,运行结果如下
[root@localhost ~]# bash shift_03.sh a b c d
Now $1 is: a, total parameter is:4
Now $1 is: c, total parameter is:2
下面的例子是利用shift来计算脚本中所有参数的和。
- [root@localhost ~]# cat shift_04.sh
#!/bin/bash
TOTAL=0
until [ $# -eq 0 ]
do
let "TOTAL=TOTAL+$1"
shift
done
echo $TOTAL
#
执行结果
[root@localhost ~]# bash shift_04.sh 10 20 30
60