Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

bash script bad substitution error message

Status
Not open for further replies.

rigstars2

Instructor
Dec 18, 2011
64
US
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

-------------
 
Well, I'm new to tek-tips (I've just registered) and I see your question has still no answer. I'm pretty sure you have the answer since, but anyway, here is mine:
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 :)
 
revised and simplified version using the new -n declaration :
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
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top