Composite Types: Associative Arrays

Learn how to declare and use associative arrays.

We'll cover the following

Associative arrays

The elements of indexed arrays are strings. Each element has an index that is a positive integer. The indexed array gives us a string by its index.

The developers introduced associative arrays in the fourth version of Bash. These arrays use strings as element indexes instead of integers. This kind of string index is called the key. The associative array gives us a string value by its string index. When do we need this feature?

Let’s suppose we need a script that stores a list of contacts. The script adds a person’s name, email, or phone number to the list. Let’s omit the person’s last name for simplicity. When we need this data back, the script prints it on the screen.

We can solve the task using an indexed array. This solution would be inefficient to search for the required contact. The script should traverse over all array elements and compare each element with the person’s name that we are looking for. When the script finds the correct person, it prints their contact information on the screen.

An associative array makes searching for contacts faster. The script should not pass through all array elements in this case. Instead, it gives the key to the array and gets the corresponding value back.

Here is an example of declaring and initializing the associative array with contacts:

declare -A contacts=(["Alice"]="alice@gmail.com" ["Bob"]="(697) 955-5984" ["Eve"]="(245) 317-0117" ["Mallory"]="mallory@hotmail.com")

Get hands-on with 1200+ tech skills courses.