Get array keys with variable name in bash
In my bash script, I have two arrays. Depending on some logic, either one or the other is used, so I get the name of the required array in a variable varName
. I can confidently get the values of this array with the code below, but is there a way to get the 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}
Thank.
source to share
Can't do without eval
, unfortunately. To be on the safe side, make sure there varName
is only one valid identifier.
[[ varName =~ ^[a-zA-Z_][a-zA-Z_0-9]+$ ]] && eval "echo \${!$varName[@]}"
eval
necessary to provide a second round of analysis and evaluation. In the first round, the shell performs normal parameter expansion, which results in the string being echo ${!foo[@]}
passed as the only argument to eval
. (Specifically, the first dollar sign was escaped and therefore passed literally, $varName
expands to foo
, and quotes are removed as part of the 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 newer you can use nameref.
declare -n varName=foo
for key in "${!varName[@]}"; do
echo "$key"
done
source to share