Associative Arrays in Bash
An associative array stores values under string keys instead of numeric positions. Where an indexed array answers "what is the third item?", an associative array answers "what is the port for https?" or "how many times has the word error appeared?". Other languages call the same structure a dictionary, map or hash table. Bash has supported associative arrays since version 4.0.
Why Associative Arrays Exist
With only indexed arrays, related data has to be kept in parallel arrays (lesson 100): one array of names, another of values, joined by sharing the same index. Looking up a value then means searching the first array for the name and reading the second array at that position. An associative array does the lookup in one step, because the name itself is the index:
declare -A port=([http]=80 [https]=443 [ssh]=22)
echo "https -> ${port[https]}"
https -> 443
Internally Bash stores associative arrays as hash tables. A key is turned into a number (its hash) that points to a slot in a table, so finding a key does not require walking through every element. For scripts this means lookups stay fast even with thousands of keys.
Declaring an Associative Array
An associative array must be declared with declare -A before it is used. This is the one array type Bash cannot create automatically:
declare -A capital
capital[France]=Paris
capital[Japan]=Tokyo
capital["United Kingdom"]=London
echo "${capital[Japan]}"
echo "${capital[United Kingdom]}"
Tokyo
London
Each assignment has the form name[key]=value. A key that contains spaces is quoted in the assignment. When reading, the text between the brackets is taken as one key, so ${capital[United Kingdom]} works even without quotes, but keys are most often held in variables, and then the variable should be quoted like any other expansion:
key="United Kingdom"
echo "${capital[$key]}"
echo "count: ${#capital[@]}"
London
count: 3
${#arr[@]} counts the keys, exactly as it counts the elements of an indexed array (lesson 101).
Compound Assignment
All the pairs can be given at once inside parentheses, with each key in brackets:
declare -A port=([http]=80 [https]=443 [ssh]=22)
declare -p port
declare -A port=([ssh]="22" [https]="443" [http]="80" )
declare -p prints the type flag -A and every key with its value. Notice that the keys are not listed in the order they were written. Bash keeps them in hash-table order, not insertion order; lesson 103 shows how to process the keys in a predictable order.
Since Bash 5.1, the pairs can also be written as a flat list of key, value, key, value:
declare -A kv=(red 1 green 2)
declare -p kv
declare -A kv=([red]="1" [green]="2" )
The bracketed form works in every Bash version with associative arrays and is easier to read, so it is the one used in this tutorial.
What Happens Without declare -A
Forgetting the declaration does not cause an error. Bash creates an indexed array instead, and the keys are evaluated as arithmetic expressions. A word like apple is treated as the name of an unset variable, which counts as 0, so every key becomes index 0:
bad[apple]=1
bad[banana]=2
declare -p bad
echo "apple: ${bad[apple]}"
declare -a bad=([0]="2")
apple: 2
Both assignments wrote to index 0, the second overwrote the first, and asking for apple returned banana's value. Nothing in the output warns about this, which is why declare -A should always be the first line that mentions an associative array. declare -p is the quickest way to check: -a means indexed, -A means associative.
Once a variable is an indexed array, it cannot be converted:
late=(x y)
declare -A late
bash: declare: late: cannot convert indexed to associative array
unset late first, then declare it again.
Keys Are Strings
Every key in an associative array is a plain string, and nothing inside the brackets is evaluated as arithmetic. Keys that look like numbers are still compared as text:
declare -A num
num[1]=one
num[01]=zero-one
num[1+1]=expr
declare -p num
declare -A num=([01]="zero-one" [1]="one" [1+1]="expr" )
1, 01 and 1+1 are three different keys. Characters that are special elsewhere are also allowed when quoted:
declare -A k
k["a b"]=1
k['$HOME']=2
k[*]=3
declare -p k
declare -A k=(["*"]="3" ["\$HOME"]="2" ["a b"]="1" )
The single quotes around $HOME keep it as literal text rather than expanding it to a directory. The one string that cannot be a key is the empty string:
bash: ek[""]: bad array subscript
If a key comes from input that might be empty, check it with [[ -n $key ]] before using it.
Reading Missing Keys
Reading a key that was never assigned gives an empty string and no error:
echo "smtp: [${port[smtp]}]"
smtp: []
To tell a missing key from a key that holds an empty value, use the -v test with the element in quotes, or the ${arr[key]+word} expansion (both were introduced for indexed arrays in lesson 101 and behave the same way here):
if [[ -v 'port[ssh]' ]]; then echo "ssh is defined"; fi
if [[ ! -v 'port[smtp]' ]]; then echo "smtp is not defined"; fi
declare -A m=([empty]="")
[[ -v 'm[empty]' ]] && echo "empty key exists"
echo "plus: [${m[empty]+yes}] [${m[none]+yes}]"
ssh is defined
smtp is not defined
empty key exists
plus: [yes] []
When the key is in a variable, use double quotes so the variable expands but the whole element is still passed as one word: [[ -v "port[$name]" ]].
A missing key can also be given a fallback with the default-value operator from lesson 45:
echo "default: ${port[smtp]:-25}"
default: 25
This only supplies a value for that one expansion. The array itself is not changed.
Updating and Removing Keys
Assigning to an existing key replaces its value. unset with the element in quotes removes the key completely:
port[http]=8080
unset 'port[ssh]'
declare -p port
declare -A port=([https]="443" [http]="8080" )
The quotes around 'port[ssh]' matter for the same reason as with indexed arrays (lesson 99): unquoted, the brackets form a glob pattern that could match a file name in the current directory. To remove a key held in a variable, write unset 'port[$name]'; Bash expands $name itself when it looks up the element, so the single quotes are correct here.
To empty the array but keep it associative, assign an empty list:
port=()
declare -p port
declare -A port=()
Appending and Counting
+= on an element appends text to the value, because values are strings:
declare -A cnt=([x]=1)
cnt[x]+=5
echo "string append: ${cnt[x]}"
string append: 15
For numbers, use arithmetic. Inside (( )), an element of an associative array can be updated like a variable, and a missing key starts at 0:
declare -A ic
ic[x]=1
(( ic[x] += 5 ))
(( ic[new]++ ))
echo "arith: ${ic[x]}"
echo "new: ${ic[new]}"
arith: 6
new: 1
Alternatively, the -i attribute makes every value an integer, so += adds instead of appending:
declare -Ai score
score[ana]=5
score[ana]+=3
echo "ana: ${score[ana]}"
ana: 8
Counting Words
Counting is the classic use of an associative array. Each word becomes a key, and its value is the number of times it has been seen:
text="the cat and the dog and the bird"
declare -A freq
for w in $text; do
(( freq[$w]++ ))
done
echo "the=${freq[the]} and=${freq[and]} cat=${freq[cat]}"
the=3 and=2 cat=1
$text is deliberately unquoted so that it splits into words (lesson 53). (( freq[$w]++ )) increases the count for the current word, creating the key with value 1 the first time.
One detail matters in scripts that use set -e (lesson 119): (( freq[$w]++ )) evaluates to the old value, which is 0 for a new key, and an arithmetic command whose result is 0 returns status 1. That status ends a set -e script on the first new word. Writing (( ++freq[$w] )) or freq[$w]=$(( ${freq[$w]:-0} + 1 )) avoids the problem, because both produce a non-zero value.
Associative Arrays in Functions
Inside a function, local -A creates an associative array that disappears when the function returns (lesson 92). This makes it a convenient scratch table, for example to detect duplicates:
find_duplicates() {
local -A seen=()
local x
for x in "$@"; do
if [[ -v "seen[$x]" ]]; then
echo "duplicate: $x"
fi
seen[$x]=1
done
echo "unique: ${#seen[@]}"
}
find_duplicates a b a c b
duplicate: a
duplicate: b
unique: 3
Only the presence of a key matters here, so the value 1 is a placeholder. Using an associative array as a set in this way is common: checking membership is one -v test instead of a loop over a list. After the function returns, seen no longer exists.
Copying an Associative Array
Writing copy=("${original[@]}") copies only the values and loses the keys. To copy keys and values, declare the target and copy each pair:
declare -A src=([a]=1 [b]=2)
declare -A dst
for k in "${!src[@]}"; do
dst[$k]=${src[$k]}
done
echo "dst a=${dst[a]} b=${dst[b]}"
dst a=1 b=2
"${!src[@]}" expands to the list of keys. Lesson 103 covers this loop and its variations in detail.
Limits to Keep in Mind
Values are single strings. A value cannot itself be an array. Lists are kept as strings with a separator (lesson 100 showed read -a splitting such a string), or in a second array.
Associative arrays cannot be exported. As with indexed arrays (lesson 97), a child process does not receive them, even with declare -Ax:
declare -Ax ex=([a]=1)
bash -c 'echo "[${ex[a]}]"'
[]
They need Bash 4.0 or later. The Bash 3.2 shipped as /bin/bash on macOS does not have them (lesson 8 explains how to install a newer Bash there). Other shells such as Dash, used as sh on Debian and Ubuntu, do not have declare at all. A three-line script assoc.sh containing declare -A m, m[a]=1 and echo ok, run with sh assoc.sh, prints:
assoc.sh: 1: declare: not found
assoc.sh: 2: m[a]=1: not found
ok
Dash reports each line as an unknown command and carries on, so the script keeps running with no array at all.
Scripts that use associative arrays should start with a Bash shebang (lesson 26) and be run with bash, not sh.
A Practical Lookup Table
Associative arrays turn chains of if or case branches into data. This script maps file extensions to a description and falls back to a default for anything unknown:
#!/usr/bin/env bash
declare -A kind=(
[sh]="shell script"
[py]="Python source"
[md]="Markdown document"
[jpg]="JPEG image"
)
for f in deploy.sh notes.md photo.jpg data.bin; do
ext=${f##*.}
echo "$f: ${kind[$ext]:-unknown type}"
done
deploy.sh: shell script
notes.md: Markdown document
photo.jpg: JPEG image
data.bin: unknown type
${f##*.} removes everything up to the last dot (lesson 54), leaving the extension, which is then used as the key. Adding a new file type is one more line in the table, with no change to the loop. The compound assignment may span several lines, and each [key]=value pair can sit on its own line for readability.
The next lesson looks at walking through all the keys and values of an associative array, sorting them, and building reports from them.