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

  • Chris says:

    I think you hit a buelslye there fellas!

  • I heard about MPB today a few weeks ago. I did a YouTube search and found your video by searching on “view count”. I was surprised that MPB has been around for 2 years, so I guess there are more ignorant people like me, but thanks to your video, I am now educated. I did verify your facts and told my other friends that were shown  MPB. The program sounds so alluring and profitable, but my “math” friends said that your video’s assessment was accurate in breaking down the winners and losers!

  • Yeah, it was close though! I got a little worried there for a while when the results were coming in.Yeah I can do that, but the problem isn’t getting the books onto the device, it’s just telling it where to go once it loads the book. I have to figure out how the KF defines what is a “book” and what is a “document”, and it isn’t just file type. Right now I’m just dealing with it, but that’s just because I’d rather do something else than research confusing stuff like that

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