Associative arrays in Bash

Arrays, both indexed and associative are a powerful and versatile data type,
regardless of the language you’re utilizing them in.

At one point in Bash’s history, pre-version 4.0, Bash only had indexed arrays.
These indexed arrays were defined as such:

# Initialize an array with values
arr=("first" "second" "third")

# Initalize an empty array and add values
arr=()
arr+=("first")
arr+=("second")
arr+=("third")

Great for maintaining simple lists of items! You can access the elements by
array index, or loop through them with a for statement.

Fast forward to the release of Bash 4.0 (I’m currently running 5.1.2 as of the
time of this writing), arrays were expanded to include the associative variety.
Before attempting to use associative arrays, be sure to check your bash version
as follows:

% bash --version
GNU bash, version 5.1.12(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Assuming you have the right version, you can start by initializing an empty
associative array using the declare statement, and populate the array with the
familiar bracket syntax:

# Initalize an associative array with values
declare -A assocArr
assocArr=(["first"]=123 ["second"]=456 ["third"]=789)

# Initalize an empty associative array and add values
declare -A assocArr
assocArr["first"]=123
assocArr["second"]=456
assocArr["third"]=789

Then instead of using an index, you can reference the values by their key:

echo "${assocArr["second"]}"

Definitely a step up when working with more complex data. Sadly though, Bash
doesn’t currently support nested arrays, but there are some tricks on how to
simulate this… which I’ll be saving for a future blog post 😉

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.