Associative Arrays
Prerequisites: Arrays
An associative array maps keys to values — like a dictionary.
It must be declared with declare -A (Bash 4 and later).
declare -A capitals=(
[France]="Paris"
[Japan]="Tokyo"
[Peru]="Lima"
)
capitals[Kenya]="Nairobi"
echo "${capitals[Japan]}"
echo "Countries: ${#capitals[@]}"
for country in $(printf '%s\n' "${!capitals[@]}" | sort); do
echo "$country → ${capitals[$country]}"
done
Tokyo
Countries: 4
France → Paris
Japan → Tokyo
Kenya → Nairobi
Peru → Lima
${capitals[key]}reads a value;${!capitals[@]}lists the keys.- Keys come back in no particular order, so sort them when order matters. (Here the keys have no spaces, so looping over the sorted output is safe.)
Counting things
declare -A count
for word in red blue red green blue red; do
(( count[$word]++ ))
done
for word in "${!count[@]}"; do
echo "${count[$word]} $word"
done | sort -rn
3 red
2 blue
1 green
Checking whether a key exists
declare -A config=([port]=8080 [debug]=false)
if [[ -v config[port] ]]; then
echo "port is set to ${config[port]}"
fi
echo "timeout: ${config[timeout]:-30 (default)}"
port is set to 8080
timeout: 30 (default)
-v tests whether a key exists (Bash 4.3+); ${config[key]:-default}
supplies a default.
Common mistakes
- Forgetting
declare -A. Without it, Bash creates an ordinary indexed array and treats every key as index0. - Using associative arrays in scripts that must run on macOS's built-in Bash 3.2, which doesn't support them.