CqN
CqN

Reputation: 283

Bash associative arrays be initialized in a (...) list?

Can bash associative arrays be initialized in a (...) list similarly to non associative arrays? Format?

Updating to give an answer using the comments.

Yes, the format depends on the version of bash. For GNU bash, version 4.4.23(1), it is declare -A AR=([key1]=value1 [key2]=value2)

The available default format can be found out with declare -p AR

Upvotes: 5

Views: 4382

Answers (2)

BadHorsie
BadHorsie

Reputation: 14544

You can create an associative array over multiple lines, for readability. Note that you do not need to quote the array keys:

declare -A person=(
    [name]='John'
    [city]='New York'
    [job]='Software Engineer'
)

echo "${person['name']}"  # John
echo "${person['city']}"  # New York
echo "${person['job']}"   # Software Engineer

Upvotes: 5

pjh
pjh

Reputation: 8064

Yes. For example:

declare -A assoc=(["1 2"]="3 4" ["a b"]="c d" )

If you've got a populated associated array (assoc say) and you want to see how it could be initialized run

declare -p assoc

That's how I got the initialization command above.

Upvotes: 5

Related Questions