🎓 A1Learner
🔍
0 of 46 lessons completed

Bash Associative Arrays in Depth

Associative arrays store values under keys, not positions. A key is a name you choose, such as a word or a label.

Count words and print in sorted key order

The first loop counts each word. The second loop prints the counts in sorted key order, so the order stays the same on every run.

declare -A count
for word in apple banana apple cherry banana apple; do
  ((count[$word]++))
done
for key in $(printf '%s\n' "${!count[@]}" | LC_ALL=C sort); do
  echo "$key: ${count[$key]}"
done

Read one count and count the distinct words

The first line reads the banana count directly. The second line counts distinct words, not total words.

declare -A count
for word in apple banana apple cherry banana apple; do
  ((count[$word]++))
done
echo "${count[banana]}"
echo "${#count[@]}"

Add the counts to find the total

The loop adds each word count to a total. The total is 6 words, while the distinct count is only 3.

declare -A count
for word in apple banana apple cherry banana apple; do
  ((count[$word]++))
done
total=0
for key in "${!count[@]}"; do
  ((total += count[$key]))
done
echo "$total"

Example

declare -A votes
for drink in tea coffee tea water tea coffee tea; do
  ((votes[$drink]++))
done
for key in $(printf '%s\n' "${!votes[@]}" | LC_ALL=C sort); do
  echo "$key: ${votes[$key]}"
done
echo "Drinks: ${#votes[@]}"

Key points

  • declare -A: declare -A counts creates an associative array named counts.
  • Key lookup: ${counts[apple]} reads the value stored under apple.
  • Counting: ((counts[$word]++)) adds one to the count for that word.
  • Sorted keys: print an associative array only through sorted keys, because raw key order is not stable.
  • Byte order sort: LC_ALL=C sort gives the same order on every run.
  • Distinct count: ${#counts[@]} counts keys, not total values.
  • Missing key: a key never stored reads as an empty value.

In this example, the loop counts each drink vote. The second loop prints every drink and its vote count in sorted key order. The last echo prints the number of distinct drinks, not the total votes.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Why should you print an associative array only through sorted keys?