'How to access associative arrays in bash

I'm having trouble accessing keys in my associative bash array.

postgresql=(["host"]="foo" ["user"]="bar")

echo "USER: ${postgresql["user"]}" # bar
echo "HOST: ${postgresql["host"]}" # bar

As you can see I get back bar for both keys. Am I doing something wrong here?



Solution 1:[1]

Use declare -A to define it:

$ declare -A postgresql=([host]='foo' [user]='bar')
$ echo "USER: ${postgresql["user"]}"
USER: bar
$ echo "HOST: ${postgresql["host"]}"
HOST: foo

Note associative arrays were introduced in Bash 4, so that they won't work if you are not using at least that version. More info in BashGuide -> Associative arrays.

I quote chepner's very useful comment below:

Associative arrays were introduced in version 4, and so unavailable in the default bash in Mac OS X. Note without a declaration, postgresql is a regular array, and the index is treated as an arithmetic expression, so the string "index" is treated as a variable whose value is 0 if the variable is unset. Your code just sets the 0th element multiple times. – chepner 8 mins ago

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community