Map String Keys to Values With Bash Associative Arrays
Use Bash 4.0+ associative arrays to map string keys to string values, with safe key checks, iteration, and removal.
03 Aug 2025, 22:11 UTC

Problem: Bash arrays only number their elements
A standard Bash array stores values at integer positions—hosts[0], hosts[1], and so on. If your script needs to look up a value by a meaningful name, such as mapping an environment name to a backend host or counting how many times each log level appears, an indexed array forces you to keep a separate parallel list of keys. That approach is fragile and hard to read.
Useful takeaway: Bash 4.0 and later provide associative arrays, declared with declare -A, which store string keys and string values much like a dictionary or map in other languages. This guide shows how to declare, populate, probe, iterate, and remove entries, along with the version and quoting rules that prevent silent bugs.
Prerequisites
- Bash version 4.0 or newer. Confirm with
bash --versionor check${BASH_VERSINFO[0]}inside a script. - Do not use this code in POSIX
shor on Bash 3.x; associative arrays are unavailable there. - No special filesystem permissions are required. Run commands in an interactive terminal or save them to a script and run
bash script.sh.
Declare and populate an associative array
Use declare -A before assigning any values. Assign with array[key]=value. Always quote the subscript when the key is held in a variable or contains spaces, so Bash does not perform globbing or word splitting.
#!/usr/bin/env bash
# Fails early on Bash older than 4.0.
if [[ "${BASH_VERSINFO[0]:-0}" -lt 4 ]]; then
echo "This script requires Bash 4.0 or later" >2
exit 1
fi
declare -A backend_by_env
backend_by_env[development]="localhost:8080"
backend_by_env[staging]="staging.internal.example.com"
backend_by_env[production]="prod.internal.example.com"
# Safe when the key comes from a variable.
key="staging"
echo "${backend_by_env[$key]}"
Expected check: the final echo prints staging.internal.example.com. If the script prints an error about declare or exits early, the shell is too old or not Bash.
Test whether a key exists
Reading a missing key under set -u raises an unbound-variable error. Test first. Bash 4.2 and later support [[ -v array[key] ]]. Bash 4.0 and 4.1 can use the +x expansion instead.
key="staging"
# Bash 4.2+
if [[ -v backend_by_env[$key] ]]; then
echo "$key is defined"
else
echo "$key is not defined" >2
fi
# Bash 4.0 and 4.1 alternative
if [[ ${backend_by_env[$key]+x} ]]; then
echo "$key is defined"
else
echo "$key is not defined" >2
fi
Expected check: with key="staging", the branch prints staging is defined. With key="qa", it prints qa is not defined to standard error.
Iterate over keys and values
Expand !array[@] to iterate keys and array[@] to iterate values. Associative arrays do not preserve insertion order, so do not rely on a particular sequence.
for env in "${!backend_by_env[@]}"; do
printf '%s => %s\n' "$env" "${backend_by_env[$env]}"
done
Expected check: each line pairs an environment name with its backend. The order may differ between runs or Bash versions.
Remove entries
Use unset to delete one entry or the whole array. This changes state immediately; there is no undo. If you need to recover, re-assign the value from a backup variable or configuration file.
unset backend_by_env[staging]
# Confirm removal.
if [[ ${backend_by_env[staging]+x} ]]; then
echo "staging still present"
else
echo "staging removed"
fi
# Clear every entry.
unset backend_by_env
Expected check: after unset backend_by_env[staging], the existence test reports that staging is gone. After unset backend_by_env, the array no longer exists at all.
Limitations and practical verification
| Behavior | Detail |
|---|---|
| Shell support | Bash 4.0+. Fails in sh, dash, and Bash 3.x. |
| Key and value types | Strings only. Nested arrays or objects are not supported directly. |
| Ordering | Iteration order is unspecified; do not assume insertion order. |
Unset keys with set -u | Triggers an unbound-variable error; test existence before reading. |
| Quoting | Quote subscripts (arr["$key"]) when keys contain spaces or glob characters. |
Practical verification: run bash --version and confirm the major version is 4 or greater. Then run a short snippet that declares an associative array, assigns one key, tests existence, iterates once, unsets the entry, and tests again. Run the same snippet under sh or Bash 3.x to confirm it fails at declare -A, proving the version dependency.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.