bash 中花括号内的感叹号和散列
Exclamation mark and hash within curly braces in bash
我正在尝试理解 bash script,但我遇到了以下行的问题:
result=${!#}
我找到了部分解决方案(!
在 ${}
内):
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; 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.
解决方案的另一部分(#
在 ${}
内)是 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.
但是我不知道这两个是怎么组合成result
的。这条线是做什么的?
${#}
是当前参数的个数shell/function:
$ set -- a b c
$ echo ${#}
3
!
进行间接参数展开,所以${#}
的值作为展开的参数名
$ echo ${!#} # same as echo
c
简而言之,${!#}
扩展为最后一个参数的值。
在没有这样的 bash
扩展的情况下,可以简单地编写一个循环,如
for result; do :; done # instead of result=${!#}
这将遍历位置参数,依次为每个参数设置 result
,一旦循环完成,将 result
保留为最后一个的值。
我正在尝试理解 bash script,但我遇到了以下行的问题:
result=${!#}
我找到了部分解决方案(!
在 ${}
内)
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; 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.
解决方案的另一部分(#
在 ${}
内)是 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.
但是我不知道这两个是怎么组合成result
的。这条线是做什么的?
${#}
是当前参数的个数shell/function:
$ set -- a b c
$ echo ${#}
3
!
进行间接参数展开,所以${#}
的值作为展开的参数名
$ echo ${!#} # same as echo
c
简而言之,${!#}
扩展为最后一个参数的值。
在没有这样的 bash
扩展的情况下,可以简单地编写一个循环,如
for result; do :; done # instead of result=${!#}
这将遍历位置参数,依次为每个参数设置 result
,一旦循环完成,将 result
保留为最后一个的值。