Associative arrays in bash

Here's my little guide on how to define and access associative arrays in bash.

Bash 4 supports associative arrays, yay! Just to recap: associative arrays are arrays with named key value pairs.

Defining the array

Let’s define an array of names

declare -A names
names[John]=Doe
names[Jane]=Doe
names[Jim]=Smith
names[Angela]=Merkel

The capital -A defines names to be an associative array.

Otherwise it breaks down to:

  ┌── array name
  |          ┌── array value
┌─┴─┐       ┌┴┐
names[John]=Doe
     └──┬─┘
        └── array key

That’s not very DRY, the names is repeated over and over. The following is better:

declare -A names
names=(
    [John]=Doe
    [Jane]=Doe
    [Jim]=Smith
    [Angela]=Merkel
)

Or even shorter like this:

declare -A names=(
    [John]=Doe
    [Jane]=Doe
    [Jim]=Smith
    [Angela]=Merkel
)

Accessing the array

Single key value pair:

echo ${names[John]}

# Outputs
Doe

How do I access the key of a single value without a loop? Unfortunately I don’t know and a quick Googling yielded no results, please leave a comment if you have info on this.

When iterating the array with a for loop, the key can be acessed with ${!names[@]} and the value with ${names[@]}:

declare -A names
names=(
    [John]=Doe
    [Jane]=Doe
    [Jim]=Smith
    [Angela]=Merkel
)

for i in "${!names[@]}"
do
    first_name=$i
    last_name=${names[$i]}
    echo "$first_name : $last_name"
done

This outputs:

John : Doe
Jane : Doe
Jim : Smith
Angela : Merkel

Add nodes to the array

This appends a node to the end of tne names array:

names+=([Zaphod]=Beeblebrox)

Other notes

The array names and values can have spaces in them, just quote them.

couples=(
    ["John Doe"]="Jane Doe"
    ["David Hasselhoff"]="Angela Merkel"
)

Conclusions

See the man page for arrays:

$ man array

Comments

Club-Mate, the beverage → club-mate.fi