• 本页内容

19. shift 命令(移位)


shift [n]

shift 命令将参数(位置参数)向左移动n个位置。 如果不指定n,参数将移动 1。

以下脚本显示了其工作原理。

$ cat shift.sh
if [ "$#" -ne "4" ]; then
    echo "Usage: ./shift one two three four"
fi
echo "Before shift:"
printf '"%b"\n' "$@" | cat -n
shift 2
echo "After shift 2:"
printf '"%b"\n' "$@" | cat -n

shift 2之后,参数 1 2 将被忽略”。 3 变为 $1 4 变为 $2

$ ./shift.sh one two three four
Before shift:
     1  "one"
     2  "two"
     3  "three"
     4  "four"
After shift 2:
     1  "three"
     2  "four"

不能传递负数来进行移位; 一旦你移动了,你就无法再移动回来。 例如,shift -2将显示以下错误:

./shift.sh: line 6: shift: -2: shift count out of range

注意:当您尝试移动的参数数量超过参数总数时,返回状态将为 1 。在上面的示例中,shift 2返回状态为 0 。 但是,如果您尝试执行shift 5,则返回状态将为 1