gpt4 book ai didi

bash - bash中大括号内的感叹号和哈希

转载 作者:行者123 更新时间:2023-12-02 16:47:41 25 4
gpt4 key购买 nike

我正在尝试理解 bash script我在使用以下行时遇到了问题:

result=${!#}

我找到了部分解决方案(!${} 中)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; 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/函数中的参数个数:

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

!进行间接参数展开,所以${#}的值作为展开的参数名。

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

简而言之,${!#} 扩展为最后一个参数的值。


在没有这样的 bash 扩展的情况下,可以简单地编写一个类似这样的循环

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

这将遍历位置参数,依次将 result 设置为每个参数,在循环完成后将 result 保留为最后一个值。

关于bash - bash中大括号内的感叹号和哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59882018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com