16.2.3 移动位置参数

在Shell中使用shift命令移动位置参数,第11章中曾简单讲到了在不加任何参数的情况下,shift命令可让位置参数左移一位,示例如下:


  1. [root@localhost ~]# cat shift_03.sh

  2. #!/bin/bash

  3. until [ $# -eq 0 ]

  4. do

  5. #

  6. 打印当前的第一个参数$1

  7. ,和参数的总个数$#

  8. echo "Now \$1 is: $1, total parameter is:$#"

  9. shift #

  10. 移动位置参数

  11. done

  12. #

  13. 运行结果

  14. [root@localhost ~]# bash shift_03.sh a b c d

  15. Now $1 is: a, total parameter is:4

  16. Now $1 is: b, total parameter is:3

  17. Now $1 is: c, total parameter is:2

  18. 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来计算脚本中所有参数的和。


  1. [root@localhost ~]# cat shift_04.sh

  2. #!/bin/bash

  3. TOTAL=0

  4. until [ $# -eq 0 ]

  5. do

  6. let "TOTAL=TOTAL+$1"

  7. shift

  8. done

  9. echo $TOTAL

  10. #

  11. 执行结果

  12. [root@localhost ~]# bash shift_04.sh 10 20 30

  13. 60