clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Associative arrays in bash

Filed under: Server— Tagged with: bash, shell

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, also known as Objects in some languages, like JavaScript.

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.

It breaks down to:

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

It can be written DRYer if so desired:

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]}
# Doe

How do I access the key of a single value without a loop? Unfortunately I don’t know and a quick search 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 accessed 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 normally:

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

Conclusions

Tip: check the man page for arrays:

$ man array

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!