简体   繁体   English

bash中花括号内的感叹号和哈希

[英]Exclamation mark and hash within curly braces in bash

I'm trying to understand a bash script and I'm having trouble with the following line:我正在尝试理解bash 脚本,但在使用以下行时遇到了问题:

result=${!#}

I found part of the solution ( ! within ${} ) here :我找到了解决方案的一部分( !${}在这里

If the first character of parameter is an exclamation point (!), it introduces a level of variable indirection.如果参数的第一个字符是感叹号 (!),则它引入了一个变量间接级别。 Bash uses the value of the variable formed from the rest of parameter as the name of the variable; Bash 使用由参数的其余部分形成的变量的值作为变量的名称; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself.这个变量然后被扩展,并且该值用于替换的其余部分,而不是参数本身的值。 This is known as indirect expansion.这称为间接扩展。

Another part of the solution ( # within ${} ) is here :解决方案的另一部分( ${} # )在这里

The length in characters of the expanded value of parameter is substituted.参数的扩展值的字符长度被替换。 If parameter is ' ' or '@', the value substituted is the number of positional parameters.如果参数是“ ”或“@”,则替换的值是位置参数的数量。 If parameter is an array name subscripted by ' ' or '@', the value substituted is the number of elements in the array.如果参数是一个以“ ”或“@”下标的数组名称,则替换的值是数组中的元素数。 If parameter is an indexed array name subscripted by a negative number, that number is interpreted as relative to one greater than the maximum index of parameter, so negative indices count back from the end of the array, and an index of -1 references the last element.如果参数是一个下标为负数的索引数组名称,则该数字被解释为相对于大于参数的最大索引的一个,因此负索引从数组的末尾开始计数,并且索引 -1 引用最后一个元素。

But I don't know how these two are combined into result .但我不知道这两者是如何组合成result What does this line do?这条线有什么作用?

${#} is the number of arguments in the current shell/function: ${#}是当前 shell/函数中的参数数量:

$ set -- a b c
$ echo ${#}
3

The ! ! performs indirect parameter expansion, so the value of ${#} is used as the name of the parameter to expand.执行间接参数扩展,因此${#}值用作要扩展的参数名称。

$ echo ${!#}  # same as echo ${3}
c

In short, ${!#} expands to the value of the last argument.简而言之, ${!#}扩展为最后一个参数的值。


In the absence of such bash extensions, one might simply write a loop like在没有这样的bash扩展的情况下,人们可能会简单地编写一个循环,如

for result; do :; done  # instead of result=${!#}

which would iterate over the positional arguments, setting result to each in turn, leaving result with the value of the last one once the loop completes.这将遍历位置参数,设置result依次到每个,留下result与最后一个一次循环完成的价值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM