Get keys of an array with variable name in bash -


in bash script have 2 arrays. depending on logic either 1 or shall used, i'm getting name of required array in variable varname. can surely values of array code below there way it's keys? tried several options no luck.

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

thanks.

not without resorting eval, unfortunately. safe, make sure varname just single valid identifier.

[[ varname =~ ^[a-za-z_][a-za-z_0-9]+$ ]] && eval "echo \${!$varname[@]}" 

eval necessary provide second round of parsing , evaluation. in first round, shell performs usual parameter expansion, resulting in string echo ${!foo[@]} being passed single argument eval. (in particular, first dollar sign escaped , passed literally; $varname expanded foo; , quotes removed part of quote removal. eval parses that string , evaluates it.

$ eval "echo \${!$varname[@]}" #       echo  ${!foo     [@]} #  above argument `eval` sees, after shell #  normal evaluation before calling `eval`. parameter #  expansion replaces $varname foo , quote removal gets #  rid of backslash before `$` , double quotes. c 

if using bash 4.3 or later, can use nameref.

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

Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -