← Back to Bash Course | Chapter 6: Arrays | Lesson 4 of 10

Associative Arrays

An associative array stores values under text keys instead of numeric positions, working like a lookup table of names to values.

Declaring an Associative Array

Associative arrays require an explicit declare -A arrname before assigning any key-value pairs, unlike indexed arrays which can be created implicitly. Once declared, values are set using string keys inside the brackets, arr["key"]=value.

Example: Declaring an Associative Array

bash
#!/bin/bash
declare -A ages
ages["Ada"]=36
ages["Grace"]=85
ages["Linus"]=54
echo "Ada's age: ${ages["Ada"]}"

Iterating Over Keys and Values

${!arr[@]} expands to all the keys currently in the associative array, and ${arr[key]} looks up the value for a specific key, so combining a loop over the keys with a lookup gives you every key-value pair. Order of iteration is not guaranteed to match insertion order.

Example: Iterating Over Keys and Values

bash
#!/bin/bash
declare -A capitals
capitals["France"]="Paris"
capitals["Japan"]="Tokyo"
capitals["Egypt"]="Cairo"
for country in "${!capitals[@]}"; do
    echo "$country -> ${capitals[$country]}"
done

Checking If a Key Exists

[[ -v arr[key] ]] tests whether a given key exists in the associative array, regardless of whether its value is empty, which is different from checking whether the looked-up value is a non-empty string. This distinction matters because a key can legitimately be set to an empty string.

Example: Checking If a Key Exists

bash
#!/bin/bash
declare -A settings
settings["debug"]=""
if [[ -v settings["debug"] ]]; then
    echo "'debug' key exists (even though its value is empty)"
fi
if [[ ! -v settings["missing"] ]]; then
    echo "'missing' key does not exist"
fi

Counting Entries and Removing a Key

${#arr[@]} gives the number of key-value pairs in an associative array, just as it does for indexed arrays. unset arr[key] removes a specific key-value pair entirely.

Example: Counting Entries and Removing a Key

bash
#!/bin/bash
declare -A stock
stock["apples"]=10
stock["bananas"]=5
echo "Entry count: ${#stock[@]}"
unset 'stock[bananas]'
echo "Entry count after removal: ${#stock[@]}"
Common Mistakes
  1. Forgetting declare -A is mandatory before using an associative array; without it, Bash treats arr[key]=value as an indexed array where a non-numeric key is coerced/misinterpreted, causing errors.
  2. Assuming associative arrays preserve insertion order when iterated; they do not guarantee any particular order for ${!arr[@]} or ${arr[@]}, unlike indexed arrays.
  3. Using unquoted keys that could be mistaken for glob patterns or contain spaces, causing lookups to fail or behave unexpectedly.
Chapter Summary
  • Must be declared explicitly first with declare -A arrname -- there is no implicit associative array creation.
  • Keys are arbitrary strings, e.g. ages["Ada"]=36, rather than sequential integers.
  • ${!arr[@]} gives all the keys; ${arr[@]} gives all the values (order is not guaranteed).
  • Checking if a key exists is done with [ -v arr[key] ] (or [[ -v arr[key] ]]) or ${arr[key]+_}, not by checking if the value is non-empty (a key could legitimately hold an empty string).

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.