$ {!#}在bash中如何工作以获取最后一个命令行参数?


19

从《高级Bash脚本指南》中,获取最后一个命令行参数:

或:lastarg=${!#} 这是对变量的 间接引用$#
请注意,lastarg=${!$#}这不起作用。


4
顺便说一句,ABS完全不适合作为参考。有关irc.freenode.org#bash频道中类事实的历史,请参见wooleedge.org/~greybot/meta/abs。的击-黑客维基Wooledge BashGuide不如声名狼藉不精确密度。在后者中,间接引用在BashFAQ#6中有详细介绍;前者是wiki.bash-hackers.org/syntax/pe#indirection
查尔斯·达菲

1
只是一个问题:不是!$更简单而且一样吗?
unxnut

Answers:


27

正如它所说的,这是一个间接参考。请看以下示例:

$ var=test
$ test='Hello, world'
$ echo ${!var}
Hello, world

现在,如果要设置以下位置参数:

$ set -- one two three

并且$#将代表位置参数的总数:

$ echo $#
3

这意味着当我像调用它一样${!#}给我一个名为的参数值时3

$ echo ${!#}
three
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.