ITEEDU

9.7. shift内建命令

9.7.1. What does it do?

shift 命令是包含在Bash内的一个Bourne shell内建命令。这个命令需要一个参数,一个数字,This command takes one argument, a number. The positional parameters are shifted to the left by this number, N. The positional parameters from N+1 to $# are renamed to variable names from $1 to $# - N+1.

Say you have a command that takes 10 arguments, and N is 4, then $4 becomes $1, $5 becomes $2 and so on. $10 becomes $7 and the original $1, $2 and $3 are thrown away.

If N is zero or greater than $# (the total number of arguments, see 第 7.2.1.2 节 “检查命令行参数”). If N is not present, it is assumed to be 1. The return status is zero unless N is greater than $# or less than zero; otherwise it is non-zero.

9.7.2. 例子

shift语句通常在事先不知道参数个数的情况下使用,比如用户可以随他们喜欢给出任意数量的参数。这种情况下,参数通常在一个 while 循环中用 (( $# )) 测试条件来处理。只要参数的数量大于零那么条件测试就为真。 $1 变量和 shift 语句处理每个参数。The number of arguments is reduced each time shift is executed and eventually becomes zero, upon which the while loop exits.

下面的例子,cleanup.sh, 使用 shift 语句来处理每个由 find 生成的列表中的文件:

#!/bin/bash

# This script can clean up files that were last accessed over 365 days ago.

USAGE="Usage: $0 dir1 dir2 dir3 ... dirN"

if [ "$#" == "0" ]; then
	echo "$USAGE"
	exit 1
fi

while (( "$#" )); do

if [[ "$(ls $1)" == "" ]]; then 
	echo "Empty directory, nothing to be done."
  else 
	find $1 -type f -a -atime +365 -exec rm -i {} \;
fi

shift

done
[注意] -exec vs. xargs

以上 find 可以使用以下来替代:

find options | xargs [commands_to_execute_on_found_files

xargs 命令从标准输入来建立执行命令行。在命令行到达系统限制的时候是有利的。只有这样才调用命令的执行,上面的例子中,将是 rm。如果没有更多的参数,一个新的命令行将被使用,直到这个until that one is full 或者没有更多的参数。同样的事情,使用 find -exec 对每次找到的一个文件调用命令来执行。因此,使用 xargs 大大地加快了脚本的运行和你机器的性能。

下面的例子中,我们修改了 第 8.2.4.4 节 “Here 文档” 的脚本让它在一次安装的时候接受多个包:

#!/bin/bash
if [ $# -lt 1 ]; then
        echo "Usage: $0 package(s)"
        exit 1
fi
while (($#)); do
	yum install $1 << CONFIRM
	y
	CONFIRM
	shift
done