🎓 A1Learner
🔍
0 of 47 lessons completed

Bash Associative Arrays

An associative array stores values under named keys. Bash reads a value by naming its key.

Store and read one pair

The declare line creates an associative array. The next line stores one value under one key.

declare -A caps
caps[france]=paris
echo "${caps[france]}"

Read a second key

Each key reads back its own value. The germany key gives berlin here.

declare -A caps
caps[france]=paris
caps[germany]=berlin
echo "${caps[germany]}"

Count the pairs

The count form works like it does for plain arrays. This array holds three pairs.

declare -A caps
caps[france]=paris
caps[germany]=berlin
caps[italy]=rome
echo "${#caps[@]}"

Example

declare -A caps
caps[france]=paris
caps[germany]=berlin
caps[italy]=rome
echo "${caps[france]}"
echo "${caps[italy]}"
echo "${#caps[@]}"

Key points

  • Use declare -A to create an associative array.
  • Write caps[france]=paris to store paris under the key france.
  • Write ${caps[france]} to read the value stored for france.
  • Write ${#caps[@]} to count the stored pairs.
  • Keys are words instead of position numbers.

In this example, the array caps stores three capital cities under country keys. The first two prints read single values by key. The last print counts all three pairs.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which line creates an associative array named caps?