Associative Arrays and Lookup Tables

Associative Arrays and Lookup Tables in Bash: At a large railway terminus, the left-luggage office takes in travellers' bags and hands back a claim tag.

The Analogy: The Left-Luggage Office and its Claim-Tag Ledger

At a large railway terminus, the left-luggage office takes in travellers' bags and hands back a claim tag. The attendant does not care where on the shelves a bag physically lands; what matters is the ledger, in which every claim tag is written next to the shelf it points to. A traveller returns hours later, presents the tag, and the attendant reads the ledger straight to the bag. The tag, not the position, is the entire means of retrieval.

This is a different filing idea from a numbered rack. There is no "bag number 3"; there is only "the bag for tag QX-88". The attendant looks a tag up directly, adds a new tag-and-shelf line when a bag arrives, crosses one out when a bag leaves, and can count the open tags to know how many bags are in the office. Two travellers may even check bags of identical contents, and the tags keep them apart -- identity lives in the tag, chosen freely, not in any running order.

The ledger's strength is also its shape: it grows in the order travellers happen to arrive, which is to say in no meaningful order at all. Reading it top to bottom gives you the tags in the sequence they were written, and that sequence carries no information -- it is not alphabetical, not by shelf, not by time of collection. When the office needs a tidy end-of-day list to reconcile against the shelves, the clerk copies the tags out and sorts them first; the raw ledger order would be useless for checking anything twice.

Two hazards live in that ledger. First, if an attendant issues a tag that is already in use, the new line overwrites the old: present the duplicated tag and you get whichever bag was filed last, while the earlier bag sits on its shelf unreachable, orphaned by a key collision that raised no alarm. Second, anyone who trusts the ledger's storage order to be a real sequence will produce a different "report" every day the arrivals differ, and will swear the records changed when only the order did. A lookup keyed by a freely chosen tag is powerful precisely because position means nothing -- and treacherous for exactly the same reason.


Syntax or Core Structure

An associative array maps arbitrary string keys to values, the way the ledger maps tags to shelves. Unlike an indexed array, it must be declared before use with declare -A; after that you assign with a string in the subscript, read a single value by its key, and count the entries with ${#map[@]}.

# declare BEFORE first use -- this is what makes it associative
declare -A color
color[apple]=red
color[lime]=green
color[plum]=purple

echo "apple is ${color[apple]}"
echo "entries: ${#color[@]}"

Output:

apple is red
entries: 3

The declare -A color line opens the ledger. Each assignment writes one tag-and-value line, ${color[apple]} looks a tag up directly, and ${#color[@]} counts the open tags. Forgetting the declare -A is the classic first mistake: without it, color[apple]=red is treated as an indexed array with the subscript evaluated as arithmetic, and every string key collapses to index 0.


Technical Depth: Reading the Ledger Without Being Fooled by Its Order

Keys, values, and iterating in a defined order

The subscript ! gives you the keys and @ gives you the values, but neither comes out in any order you can rely on -- the ledger yields its lines in insertion-hash order, which differs between Bash builds and means nothing to a reader. To print a repeatable list you must sort the keys yourself.

declare -A price
price[apple]=40
price[lime]=15
price[plum]=60

for k in $(printf '%s\n' "${!price[@]}" | sort); do
  echo "$k -> ${price[$k]}"
done

Output:

apple -> 40
lime -> 15
plum -> 60

The printf '%s\n' "${!price[@]}" | sort step is the clerk copying tags out and alphabetising them before the reconciliation. Iterating "${!price[@]}" directly would "work" and even look stable on one machine, but it is exactly the unordered ledger read the analogy warns against.

One caution about the sort itself: plain sort compares keys as text, so numeric keys come out in dictionary order -- 10 sorts before 2, and 100 before 20. When your keys are numbers, sort with sort -n so they order by value; when the keys mix text and numbers, decide deliberately which ordering the report needs rather than accepting whichever the default comparison happens to give. The associative array hands back exactly the same set of keys either way -- choosing a stable, meaningful order for them is your responsibility, not something the array will ever do for you.

ExpressionWhat it yields
${map[key]}the value for one key (empty if absent)
${!map[@]}all keys, in unreliable order
${map[@]}all values, in unreliable order
${#map[@]}the number of entries

Testing for a key and supplying defaults

A lookup on a missing key returns the empty string, which is ambiguous: it could mean "no such key" or "the key exists and its value is empty". The -v test inside [[ ... ]] distinguishes the two -- it is true when the key is present regardless of its value -- and ${map[key]:-default} supplies a fallback for the absent-or-empty case.

declare -A cfg
cfg[host]=localhost
cfg[port]=""

for key in host port timeout; do
  if [[ -v cfg[$key] ]]; then
    echo "$key is set to '${cfg[$key]}'"
  else
    echo "$key is not set (default 30)"
  fi
done

Output:

host is set to 'localhost'
port is set to ''
timeout is not set (default 30)

Notice the middle line: port was assigned an empty string, so -v reports it as set even though its value prints as nothing, while timeout was never written and falls to the default branch. Relying on [ -z "${cfg[port]}" ] alone would wrongly treat the deliberately-empty port as missing -- the distinction between "absent" and "present but empty" is real and -v is how you honour it.

An associative array as a set

Because a key can exist independently of any meaningful value, an associative array is the natural way to model a set: store seen[$item]=1 and test membership with [[ -v seen[$item] ]]. This turns deduplication and "have I handled this already?" checks into constant-time lookups instead of repeated linear scans of a list.

declare -A seen
dropped=0
for w in apple lime apple plum lime apple; do
  if [[ -v seen[$w] ]]; then
    dropped=$(( dropped + 1 ))
  else
    seen[$w]=1
  fi
done
echo "distinct count: ${#seen[@]}"
echo "dropped: $dropped"
for w in $(printf '%s\n' "${!seen[@]}" | sort); do
  echo "- $w"
done

Output:

distinct count: 3
dropped: 3
- apple
- lime
- plum

Six words go in, three are already present when their turn comes, and the set keeps exactly one of each. The value 1 is a placeholder that never matters; all the meaning lives in whether the key is present, which is precisely what -v asks. Printing the members still needs the sort, because a set has no more inherent order than the ledger did.

Passing a map to a function with a nameref

Bash cannot pass an array to a function by value, so a function that must update a caller's map takes the array's name as an argument and binds it with local -n. The nameref ref then reads and writes the caller's array directly, as if it were a local alias for it.

declare -A inventory
inventory[bolts]=120
inventory[nuts]=80

add_stock() {
  local -n ref=$1
  local item=$2 qty=$3
  ref[$item]=$(( ${ref[$item]:-0} + qty ))
}

add_stock inventory bolts 30
add_stock inventory washers 45

for item in $(printf '%s\n' "${!inventory[@]}" | sort); do
  echo "$item: ${inventory[$item]}"
done

Output:

bolts: 150
nuts: 80
washers: 45

The first call bumps an existing key; the second seeds a brand-new one through the same :-0 default. Namerefs have one sharp edge worth remembering: if the local nameref happens to share its name with the caller's variable (here, calling the parameter inventory instead of ref), Bash detects the circular reference and the binding fails, so pick a distinct internal name.


Real World Example: A Frequency Tally by Category

The archetypal job for an associative array is counting: how many times each distinct value appears in a stream. Here a script reads log lines, takes the first field as a severity level, and tallies how many lines carried each level -- a lookup table whose keys are discovered from the data itself rather than known in advance.

#!/usr/bin/env bash
# tally.sh -- count occurrences of each first-field token, print sorted by name
set -uo pipefail

declare -A count

while read -r level _; do
  [ -n "$level" ] || continue
  count[$level]=$(( ${count[$level]:-0} + 1 ))
done

for level in $(printf '%s\n' "${!count[@]}" | sort); do
  printf '%-7s %d\n' "$level" "${count[$level]}"
done

Fed six lines covering three levels, it reports each level once, in alphabetical order, with its count:

bash tally.sh <<'LOG'
INFO started
WARN low disk
INFO request
ERROR timeout
WARN retry
INFO done
LOG

Output:

ERROR   1
INFO    3
WARN    2

The keys were never declared in the script; they appeared as the data was read, which is the whole point of a lookup table over a fixed set of variables. Each line's first field indexes the ledger, the count for that key is bumped by one, and at the end the keys are pulled out and sorted so the report reads the same on every run and every machine.

One detail in the increment is load-bearing. The line reads count[$level]=$(( ${count[$level]:-0} + 1 )) rather than the tidier (( count[$level]++ )) because, under set -u, incrementing a key that does not yet exist raises an "unbound variable" error and aborts the script on the very first line of a new level. The :-0 default seeds the missing key with zero before adding one, which is the safe idiom whenever set -u is in force.

The script is honest but limited. It sorts alphabetically, not by frequency, so it answers "which levels appeared" rather than "which was most common" -- a genuine design flaw if you expected a ranked chart, and fixing it means sorting the values instead of the keys. It is also case-sensitive, so INFO and info would be tallied as two separate levels, and read -r level _ keeps only the first whitespace-delimited token as the key, silently folding everything after it into the ignored _. None of these are bugs in the counting itself, but each is an assumption a caller could trip over.


Common Mistakes

  1. Forgetting declare -A. Without it, map[key]=value creates an ordinary indexed array and evaluates the key as arithmetic, so every non-numeric key becomes index 0 and each write clobbers the last. The declare -A must come before the first assignment.
  1. Trusting the iteration order. ${!map[@]} returns keys in an insertion-hash order that varies between Bash builds. Any output that lists the whole map must sort the keys first, or the "same" script prints different orders on different machines.
  1. Confusing a missing key with an empty value. ${map[key]} is empty in both cases. Use [[ -v map[key] ]] when you genuinely need to tell "never set" from "set to empty".
  1. Incrementing under set -u with (( map[k]++ )). On a key that does not yet exist this raises an unbound-variable error and aborts. Seed it with map[k]=$(( ${map[k]:-0} + 1 )) instead.
  1. Using ${map[*]} expecting key-value pairs. ${map[*]} and ${map[@]} give only the values; the keys come from ${!map[@]}. To print pairs you must iterate the keys and look each value up.
  1. Quoting keys with spaces incorrectly. A key that contains spaces must be quoted on write and read: map["full name"]=x and ${map["full name"]}. Unquoted, the space splits the subscript and corrupts the key.
  1. Assuming keys are ordered numerically. Even if every key is a number, an associative array does not keep them sorted; ${!map[@]} on numeric keys is still hash-ordered, not 1 2 3.
  1. Copying with new=("${old[@]}"). That copies the values into an indexed array and throws the keys away. To duplicate an associative array you must re-declare with -A and copy key by key.
  1. Passing an associative array to a function by value. Bash cannot pass one as an argument; you must pass its name and use declare -n (a nameref) inside the function, or operate on a global. Forgetting this yields an empty array in the callee.

Best Practices

  • Always declare -A before first use. Make the declaration the first thing readers see, so the intent -- a keyed lookup, not a numbered list -- is unmistakable and the arithmetic-subscript trap never fires.
  • Sort keys before printing. Pipe "${!map[@]}" through sort (or sort -n for numeric keys) whenever output must be reproducible; never emit raw hash order to a report or a diff.
  • Use [[ -v map[key] ]] to test existence. Reserve empty-string checks for when you truly mean "empty", and use -v when you mean "present".
  • Seed counters with ${map[k]:-0} under set -u. It keeps the safety of set -u while letting keys spring into existence on first sight.
  • Quote keys that may contain spaces or globs. Write map["$key"]=... and read ${map["$key"]} so an unusual key cannot split or expand.
  • Prefer namerefs for passing maps to functions. Take the array's name as an argument and bind it with local -n ref=$1; it is the only clean way to share an associative array with a function.
  • Keep keys in one canonical case. Normalise with ${key,,} or ${key^^} before indexing if the data may vary in case, so INFO and info do not become two entries.
  • Choose associative arrays for membership and dedup too. Setting seen[$x]=1 and testing [[ -v seen[$x] ]] is a fast, clear set; do not reach for repeated linear searches of an indexed array.

Practice Exercises

  1. Word frequency, ranked. Extend the tally script so it prints the levels ordered by count, highest first, breaking ties alphabetically. Sort the output lines rather than the keys, and explain in a comment why sorting the keys cannot achieve a frequency order.
  2. Config with defaults. Build an associative array of settings, then write a get function that returns ${cfg[$1]} when the key exists and a supplied fallback otherwise, using [[ -v cfg[$1] ]] to tell absent from empty. Demonstrate it on one present key, one empty key, and one missing key.
  3. Deduplicate a list. Read a list of words that contains repeats and print each distinct word once, in sorted order, using an associative array as a set (seen[$word]=1). Report how many duplicates were dropped.
  4. Invert a lookup. Given a map from usernames to user IDs, build the reverse map from IDs to usernames, and print it sorted by ID. State what your code does if two usernames share an ID, and why that is a key collision.