Shell shift过程 - 这是什么?

19

在shell中,我们有一个命令叫做shift,但是我在一些例子中看到它后面跟着数字"shift 3"。

为什么shift后面会有一个数字?这个数字是什么意思?它是用来做什么的?

示例:

echo “arg1= $1  arg2=$2 arg3=$3shift
echo “arg1= $1  arg2=$2 arg3=$3shift   
echo “arg1= $1  arg2=$2 arg3=$3shift  
echo “arg1= $1  arg2=$2 arg3=$3shift
输出结果为:
arg1= 1 arg2=2  arg3=3 
arg1= 2 arg2=3  arg3= 
arg1= 3 arg2=   arg3=
arg1=   arg2=   arg3=

但是当我添加那个时,它不能正确地显示。


shift 3本质上与shift; shift; shift相同。 - Mark Reed
5个回答

49

请查看man页面,上面写道:

shift [n]
    The  positional parameters from n+1 ... are renamed to $1 .... 
    If n is not given, it is assumed to be 1.
一个示例脚本:
#!/bin/bash
echo "Input: $@"
shift 3
echo "After shift: $@"

运行它:

$ myscript.sh one two three four five six

Input: one two three four five six
After shift: four five six

这表明在向右移动3位后,$1=four$2=five$3=six


2

您可以使用man bash命令查找shift内置命令:

shift [n]

n + 1个位置参数将被重命名为$1......,编号为$#至$#-n+1的参数将被取消设置。n必须是小于或等于$#的非负数。如果n为0,则不更改任何参数。如果未给出n,则假定为1。如果n大于$#,则不更改位置参数。如果n大于$#或小于零,则返回状态大于零;否则为0。


1
这个问题可以通过阅读Bash手册或输入man shift来简单回答:
      shift [n]

Shift the positional parameters to the left by n. The positional parameters from n+1 ... $# are renamed to $1 ... $#-n. Parameters represented by the numbers $# to $#-n+1 are unset. n must be a non-negative number less than or equal to $#. If n is zero or greater than $#, the positional parameters are not changed. If n is not supplied, it is assumed to be 1. The return status is zero unless n is greater than $# or less than zero, non-zero otherwise.


1
不确定为什么,但我没有shift的手册条目。也许这取决于发行版,但bash手册也有它。 - iyrin

0

0

将位置参数向左移动n个位置。从n+1到$#的位置参数被重命名为$1到$#-n。由数字$#到$#-n+1表示的参数被取消设置。n必须是小于或等于$#的非负数。如果n为零或大于$#,则位置参数不会更改。如果未提供n,则假定为1。返回状态为零,除非n大于$#或小于零,否则为非零。

  1. 列表项

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接