移动参数
bash shell 工具箱中的另一件工具是 shift 命令,该命令可用于操作命令行参数。跟字面上的意思一样,shift 命令会根据命令行参数的相对位置进行移动。
在使用 shift 命令时,默认情况下会将每个位置的变量值都向左移动一个位置。因此,变量$3 的值会移入$2,变量$2 的值会移入$1,而变量$1 的值则会被删除。
注意:变量$0 的值,也就是脚本名,不会改变
例:
- $ cat shiftparams.sh
- #!/bin/bash
- # Shifting through the parameters
- #
- echo
- echo "Using the shift method:"
- count=1
- while [ -n "$1" ]
- do
- echo "Parameter #$count = $1"
- count=$[ $count + 1 ]
- shift
- done
- echo
- exit
- $
- $ ./shiftparams.sh alpha bravo charlie delta
- Using the shift method:
- Parameter #1 = alpha
- Parameter #2 = bravo
- Parameter #3 = charlie
- Parameter #4 = delta
- $
也可以一次性移动多个位置。只需给 shift 命令提供一个参数,指明要移动的位置数即可:
- $ cat bigshiftparams.sh
- #!/bin/bash
- # Shifting multiple positions through the parameters
- #
- echo
- echo "The original parameters: $*"
- echo "Now shifting 2..."
- shift 2
- echo "Here's the new first parameter: $1"
- echo
- exit
- $
- $ ./bigshiftparams.sh alpha bravo charlie delta
- The original parameters: alpha bravo charlie delta
- Now shifting 2...
- Here's the new first parameter: charlie'
- $