danaso, did you quote the list of cities for each person, or did you quote each city individually? Things seem to work fine tfor me when I do the former. Here's a (slightly edited) transcript of my Bash session:
$ declare -A myArray=([emma]="paris london ny" [john]="tokyo LA")
Or, to create your associative array on the fly, as in your "actual code", from the regular arrays called names
and cities
, you would first create these arrays, like this:
$ declare -a names=(emma john) # Notice: small '-a' for inexed array.
$ declare -a cities=("paris london ny" "tokyo LA") # Notice: Quotes around whole lists of cities!
Then I would start with an empty myArray
and build it up in a loop, like this:
$ declare myArray=()
for i in ${!names[@]}; do
name=${names[$i]}
city=${cities[$i]}
myArray+=([$name]=$city)
done
As an aside: Sometime in the future, you may want to populate myArray
in this manner, but with different entries in your cities
and names
. If and when you do, it will be a good iea to set -o noglob
before the for
-loop. This disables pathname expansion by the shell and guards against trouble when you accidentally have a name or city called *
in one of your arrays. You can re-enable it with set +o noglob
after the for
-loop.
Anyway, no matter which way you populate myArray
, the new cities no longer overwrite the previous, as you can see:
$ echo ${myArray[emma]}
paris london ny
$ echo ${myArray[john]}
tokyo LA
And you can process the cities individually, such as in this for
-loop:
$ for city in ${myArray[emma]}; do echo "hello, $city!"; done
hello, paris!
hello, london!
hello, ny!
How does that work for you?
PS: I'd like to thank Charles Duffy for the improvements to my code that he suggested in the comments.