在bash中获取具有变量名称的数组的键(Get keys of an array with variable name in bash)

系统教程 行业动态 更新时间:2024-06-14 16:55:57
在bash中获取具有变量名称的数组的键(Get keys of an array with variable name in bash)

在我的bash脚本中,我有两个数组。 根据某些逻辑,将使用一个或另一个,因此我在变量varName获取所需数组的名称。 我可以使用下面的代码获取此数组的值,但有没有办法获取它的键? 尝试了几个选项,但没有运气。

declare -A foo=([a]=b [c]=d) declare -A bar=([e]=f [g]=h) varName=foo varArray=$varName[@] echo ${!varArray}

谢谢。

In my bash script I have two arrays. Depending on some logic either one or another shall be used, so I'm getting the name of a required array in a variable varName. I can surely get the values of this array with the code below but is there a way to get it's keys? Tried several options but no luck.

declare -A foo=([a]=b [c]=d) declare -A bar=([e]=f [g]=h) varName=foo varArray=$varName[@] echo ${!varArray}

Thanks.

最满意答案

不幸的是,并非没有依靠eval 。 为安全起见,请确保varName 只是一个有效的标识符。

[[ varName =~ ^[a-zA-Z_][a-zA-Z_0-9]+$ ]] && eval "echo \${!$varName[@]}"

eval是提供第二轮解析和评估所必需的。 在第一轮中,shell执行通常的参数扩展,导致字符串echo ${!foo[@]}作为单个参数传递给eval 。 (特别是,第一个美元符号被转义,因此按字面意思传递; $varName扩展为foo ;并且引号被删除作为引用删除的一部分eval然后解析字符串并对其进行评估。

$ eval "echo \${!$varName[@]}" # echo ${!foo [@]} # The above is the argument that `eval` sees, after the shell # does the normal evaluation before calling `eval`. Parameter # expansion replaces $varName with foo and quote removal gets # rid of the backslash before `$` and the double quotes. a c

如果您使用的是bash 4.3或更高版本,则可以使用nameref。

declare -n varName=foo for key in "${!varName[@]}"; do echo "$key" done

Not without resorting to eval, unfortunately. To be safe, make sure varName is just a single valid identifier.

[[ varName =~ ^[a-zA-Z_][a-zA-Z_0-9]+$ ]] && eval "echo \${!$varName[@]}"

eval is necessary to provide a second round of parsing and evaluation. In the first round, the shell performs the usual parameter expansion, resulting in the string echo ${!foo[@]} being passed as the single argument to eval. (In particular, the first dollar sign was escaped and so is passed literally; $varName is expanded to foo; and the quotes are removed as part of quote removal. eval then parses that string and evaluates it.

$ eval "echo \${!$varName[@]}" # echo ${!foo [@]} # The above is the argument that `eval` sees, after the shell # does the normal evaluation before calling `eval`. Parameter # expansion replaces $varName with foo and quote removal gets # rid of the backslash before `$` and the double quotes. a c

If you are using bash 4.3 or later, you can use a nameref.

declare -n varName=foo for key in "${!varName[@]}"; do echo "$key" done

更多推荐

本文发布于:2023-04-10 11:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/cacbc08556fc1a805c1af69d731ae7b7.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   变量   名称   bash   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!