I am having a bit of trouble while looping through multiple associative arrays in bash.
Here is the code I'm running: (stripped of the actual information)
arrays=("arrayone" "arraytwo")
declare -A arrayone=(["one"]=1 ["two"]=2)
declare -A arraytwo=(["text with spaces"]=value ["more text with spaces"]=differentvalue)
for array in ${arrays[*]}
do
for key in $(eval echo $\{'!'$array[@]\})
do
echo "$key"
done
done
This works perfectly fine until I run into a key value that has spaces in it. No matter what I do, I cannot get items with spaces to be treated correctly.
I would appreciate any ideas you have on how to get this working. If there is, a better way to do this, I'd be happy to hear it. I don't mind scratching this and starting over. It's just the best I've been able to come up with so far.
Thanks!
[@]is needed to preserve spaces.$()is going to throw that away even if you get the internal expansion right. I don't think you can do it this way. You probably need to write a function for the inner loop and pass it$array[@]and do the indirect expansion in the function. LikeisSubsetfrom here.tmp="${array}[@]"; for elem in "${!tmp}"; ...-- however, using that idiom, you can't iterate over the keys: this does not work:tmp='!'"${array}[@]"; for key in "${!tmp}"; ...-- this${!tmp}expands to nothing. You may be reduced to parsing the output ofdeclare -p "$array"