bash script bad substitution error message
bash script bad substitution error message
(OP)
Each item in the list is an associated array. I'm trying to traverse each key/value from each associated array. Error message I get ... ${!$x[@]}: bad substitution
I tried substituting with backticks and quotations ..
aaList=( aa1 aa2 aa3 )
for x in "${aaList[@]}"
do
for KEY in "${!$x[@]}"; do
echo "$KEY" "${$x[$KEY]}"
done
echo
done
-------------
I tried substituting with backticks and quotations ..
aaList=( aa1 aa2 aa3 )
for x in "${aaList[@]}"
do
for KEY in "${!$x[@]}"; do
echo "$KEY" "${$x[$KEY]}"
done
echo
done
-------------
RE: bash script bad substitution error message
parameter expansion does not accept nesting (you can't do ${${var}}. You can have an indirection with '!' ( ${!var} ), but in the case of associative arrays, the indirection is used to access the keys ( "${!AA[@]}" ). Anyway, what follows the opening '{' (or the '!' - or '#' following it) is necessarily a NAME and not another parameter expansion. So you have to transform the parameter expansion of x first to the final name of the array variable.
Example :
$ unset a b ; declare -A a b ; for i in k{1..6} ; do a[a$i]=a_val_$i b[b$i]=b_val_$i ; done ; echo -e "${a[@]}\n${b[@]}"
a_val_k1 a_val_k2 a_val_k3 a_val_k4 a_val_k5 a_val_k6
b_val_k6 b_val_k5 b_val_k4 b_val_k3 b_val_k2 b_val_k1
declare -a c
c=( a b )
for x in "${c[@]}" ; do for k in $( eval echo "\${!$x[@]}" ) ; do echo -n "$k = " ; eval echo "\${$x[$k]}" ; done ; done
ak1 = a_val_k1
ak2 = a_val_k2
ak3 = a_val_k3
ak4 = a_val_k4
ak5 = a_val_k5
ak6 = a_val_k6
bk6 = b_val_k6
bk5 = b_val_k5
bk4 = b_val_k4
bk3 = b_val_k3
bk2 = b_val_k2
bk1 = b_val_k1
Not so straightforward as you thought ... but it works :)
RE: bash script bad substitution error message
unset a b c x
declare -A a b ; for i in k{1..2} ; do a[a$i]=a_val_$i b[b$i]=b_val_$i ; done ; echo -e "${a[@]}\n${b[@]}"
declare -n x
declare -a c=( a b )
for x in "${c[@]}" ; do for k in "${!x[@]}" ; do echo -n "$k = " ; echo "${x[$k]}" ; done ; done