Free — no signup required

Associative Arrays: Dictionaries in Bash

1 min read

Key-Value Pairs

An indexed array is a list. Sometimes you need a map: a structure that associates a name (key) with a value. In Python this is a dictionary; in Bash 4.0+ it is an associative array.

You must declare associative arrays explicitly before use. Without that explicit declaration, Bash treats the variable as an ordinary indexed array and silently ignores string keys — a subtle failure mode where the array looks like it's working but every key collapses to the same numeric slot.

Values are set and read by string key rather than numeric index, existence of a key can be checked directly without touching its value, and looping over "${!MAP[@]}" — the ! prefix — iterates the keys; the same expansion without the ! iterates the values instead.

Key Point: Associative arrays require Bash 4.0 or later. macOS ships with Bash 3.2 by default (due to licensing), which does not support them. Scripts using associative arrays that need to run on macOS must either require the user to install Bash 4+ via Homebrew, or use a workaround (like encoding key-value pairs in regular strings). Always check bash --version if portability matters.

This is one of 18 chapters

Every chapter is free — Kubernetes, Terraform, SRE, distributed systems, and more — with fast daily review built in.

Sign up free