${@:2} 是什么意思

1.这是GNU Bash的官方文档:https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion

2. 其中第3.4节讲了Shell参数有两种取法:可定位参数(Positional Parameters)和特殊参数(Special Parameters)

Positional Parameters:The shell’s command-line arguments. Shell命令行入参
Special Parameters:Parameters denoted by special characters. 通过特殊字符表示的参数

3. 可定位参数(Positional Parameters)

A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using thesetbuiltin command. Positional parameterNmay be referenced as${N}, or as$NwhenNconsists of a single digit. Positional parameters may not be assigned to with assignment statements. Thesetandshiftbuiltins are used to set and unset them (seeShell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (seeShell Functions).

即可以通过非0的数字定位参数,0为命令本身,1,2,3,4,5,,,为命令后面的参数

4. 特殊参数(Special Parameters)

Shell对几个参数特殊对待,下列参数只能被引用,不能被赋值
*
  ($*)从1开始展开可定位参数, 当使用没有被双引号括起时,每个可定位参数展开一个独立的词。在被使用的时候,
  这些词可以被再次分割或路径展开。当有被双引号括起时,它将展开为一个词(也可以理解为合并为一个词),
  为"$1c$2C.."形式,c为IFS变量的首字母,如果IFS没有设置,由c为空格,如果IFS为null,则中间没有间隔
@
  ($@)从1开始展开可定位参数,在被使用的时候,默认展开为独立的多个词,如果没有被双引号括起来,这些词被
  用来做单词分割。当没有被做分割使用时,它展开(也理解为合并)为一个由空格拼接出来的一个词。当有被双引号
  括起且被单词分割时,每个参数展开为独立的词,即,"$@"等同于"$1" "$2" ...。
  (这里有一段话没太理解,和这个问题关系不大,先不翻译了)。
  如果没有任何可定位参数,则"$@"和$@展开为无,即它们被删除了。

5. 第3.5.3节讲了Shell参数展开

${parameter:offset}
${parameter:offset:length}

通过这种方式可以截取字符串或数组

If parameter is ‘@’, the result is length positional parameters beginning at offset. A negative offset is taken relative to one greater than the greatest positional parameter, so an offset of -1 evaluates to the last positional parameter. It is an expansion error if length evaluates to a number less than zero.

如果参数为@,则为截取可定位参数数组,从offset开始算,length为取的长度,如果不给,则取到最后。如果offset为负,则为从最后一位倒数,如offset为-1则为最后一个元素。如果offset和length计算得到的长度小于0则会报错

The following examples illustrate substring expansion using positional parameters:

后面为示例

$ set -- 1 2 3 4 5 6 7 8 9 0 a b c d e f g h
$ echo ${@:7}
7 8 9 0 a b c d e f g h
$ echo ${@:7:0}

$ echo ${@:7:2}
7 8
$ echo ${@:7:-2}
bash: -2: substring expression < 0
$ echo ${@: -7:2}
b c
$ echo ${@:0}
./bash 1 2 3 4 5 6 7 8 9 0 a b c d e f g h
$ echo ${@:0:2}
./bash 1
$ echo ${@: -7:0}

所以,echo "${@:2}" ,它的意思就是输出入参的第2个至最后一个参数,且以空格分隔,合并为一个单词(word)

转自知乎刘长远的答复:https://www.zhihu.com/question/368661192/answer/991165910

Leave a Reply

Your email address will not be published. Required fields are marked *