$_ CLI In Depth
Learning progress 0%
lesson functions arrays parameter-expansion

Associative Arrays

4 min read Module 14: Functions, Arrays & Parameter Expansion Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:15

Declaring the array

You must declare an associative array with declare -A before you assign to it. Without the declaration, bash treats a key such as apple as an arithmetic expression, which usually evaluates to zero and silently stores the value in element zero of an ordinary array. This is the single most common mistake with associative arrays, so make the declaration a habit.

BASH4 lines
declare -A color
color[apple]=red
color[lime]=green
echo "apple is ${color[apple]}"

The output is apple is red. Keys are ordinary strings. They are not sorted and they are not numbered, and the order in which bash returns them is not something to rely on.

Keys with spaces and special characters

A key that contains a space or a character with meaning to the shell must be quoted in the subscript. The quotes protect the key from word splitting and globbing, in the same way they protect ordinary words. Inside the subscript of an associative array, quoting is the rule that makes the key exact.

BASH5 lines
declare -A color
color["light green"]=pale
color[dark*]=star
echo "${color[light green]}"
echo "${color["light green"]}"

The last echo prints pale, because the subscript is quoted and names exactly one key. Writing the same key without quotes, as in ${color[light green]}, does not name one key at all: the subscript is split at the space and the lookup fails or reads the wrong entry. The star key is stored safely because an assignment subscript is not globbed, but a read of the same key should also be quoted.

Warning

Always quote the subscript of an associative array in both assignments and reads, for example "${color[$key]}" when the key is in a variable. An unquoted key with a space is split into words, and the lookup fails silently.

Listing keys and values

The expansion ${!color[@]} lists the keys, and ${color[@]} lists the values. Both work with quoted forms that produce one word per item. The number of entries is ${#color[@]}. Because the order is not guaranteed, sort the keys when you print them.

BASH6 lines
declare -A color
color[apple]=red
color[lime]=green
for k in $(printf "%s\n" "${!color[@]}" | sort); do
  echo "$k=${color[$k]}"
done

The loop prints apple=red and then lime=green. The keys are passed through sort, so the output order is stable. The inner printf prints one key per line, and the command substitution splits them into words that the for loop reads. That only works because the keys in this example contain no spaces. For keys with spaces, use a while read loop over the sorted output instead.

Checking whether a key exists

An empty value and a missing key look the same when you read them. To test for a key, use the -v test on the array element, which is true when the key is set even if the value is empty. Bash 4.3 and later support this form.

BASH4 lines
declare -A color
color[apple]=
if [[ -v color[apple] ]]; then echo "apple is set"; fi
if [[ -v color[pear] ]]; then echo "pear is set"; else echo "pear is missing"; fi

The output is apple is set followed by pear is missing, even though the apple value is empty. Without the -v test, an empty value would look the same as a missing key and the script would make the wrong decision.

Using a map as a counter

A common use of an associative array is counting. Each time you see a word, you add one to the count stored under that word. The arithmetic form ((counts[$w]++)) works on associative arrays, so you do not need a separate lookup step.

BASH3 lines
declare -A counts
for w in red blue red green red; do ((counts[$w]++)); done
for k in $(printf "%s\n" "${!counts[@]}" | sort); do echo "$k ${counts[$k]}"; done

The output is blue 1, green 1, and red 3. The same pattern works for counting log levels, file extensions, or any category, which is why associative arrays replace many uses of sort | uniq -c inside a script.

Hands-on: a lookup table

Type the block below. It declares a map of short codes to names and prints one entry. The lab for this unit writes the same map into a script and checks the output, so that you practice the declaration and the quoting outside your interactive shell.

BASH4 lines
declare -A code
code[US]="United States"
code[IN]="India"
echo "${code[IN]} has ${#code[@]} entries in this map"

The output is India has 2 entries in this map. The count reflects the two keys that were set.

Terminal lab · 2 steps · real Linux in your browser

Map keys to values

Build a sorted map from keys to values, then handle a key that contains a space.

01
Print a sorted map
Create map.sh in /workspace. It declares an associative array, sets apple to red and lime to green, and prints each key with its value in sorted key order: ``bash cat > map.sh <<'EOF' declare -A color color[apple]=red color[lime]=green for k in $(printf "%s\n" "${!color[@]}" | sort); do echo "$k=${color[$k]}" done EOF ``
Show hint for step 1
The declare -A line must come first. Without it, bash does not store the string keys.
02
Quote a key with a space
Create map2.sh in /workspace. It stores apple as red and the key light green as pale. It prints the number of entries, then the value of the light green key through a quoted variable: ``bash cat > map2.sh <<'EOF' declare -A color color[apple]=red color["light green"]=pale echo "count=${#color[@]}" v="${color["light green"]}" echo "light green=$v" EOF ``
Show hint for step 2
Put the key in double quotes inside the subscript so the space does not split it.
Check yourself Question 1 of 4
Concept Check Required declaration recall

Which declaration must come before assigning string keys to an array in bash?

Recap & Key Takeaways

declare -A must come before an assignment, or bash treats the string key as an arithmetic expression and stores the value in the wrong place.
Quote the subscript of an associative array, because keys with spaces or wildcards are otherwise split or expanded.
${!name[@]} lists the keys, ${name[@]} lists the values, and [[ -v name[key] ]] tests for a key even when its value is empty.
Associative arrays are useful for counting and lookup tables, and you should sort keys before printing them because their order is not guaranteed.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue