在我的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" doneNot 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 cIf 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更多推荐
发布评论