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

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

It breaks down to:

  ┌── array name
  |          ┌── array value
┌─┴─┐       ┌┴┐
        └── array key

It can be written DRYer if so desired:

declare -A names

Or even shorter like this:

declare -A names=(

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

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

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:


Other notes

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

  ["John Doe"]="Jane Doe"
  ["David Hasselhoff"]="Angela Merkel"


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!