Reputation: 33
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!
Upvotes: 3
Views: 797
Reputation: 77137
Bash added the nameref attribute in 4.3. It allows you to make a name specifically a reference to another. In your case, you would do
declare -A assoc_one=(["one"]=1 ["two"]=2)
declare -A assoc_two=(["text with spaces"]=value ["more text with spaces"]=differentvalue)
declare -n array # Make it a nameref
for array in "${!assoc_@}"; do
for key in "${!array[@]}"; do
echo "'$key'"
done
done
and you get
'one'
'two'
'text with spaces'
'more text with spaces'
Names were changed to protect the idioms. I mean, I changed the array names so I could do "${!assoc_@}"
without making array
a special case.
Upvotes: 4