Bash Associative Arrays with Examples

Last updated: May 4, 2023 | Linuxopsys

A Bash variable only holds a single value. To hold multiple values at the same time, we bring arrays into the picture. An array is a mere collection of items holding some information. Bash arrays are unique as they can save different types of elements. If the size of the array is unknown, associative arrays are preferred. Since they associate the value and the index together, they are called associative arrays. In this tutorial, we will learn about these arrays, which store entries like a map.

What are associative arrays?

The bash arrays can be broadly categorized into numerically indexed arrays and associative arrays. In indexed arrays, elements are stored and assigned an integer number starting from 0. Associative arrays behave like a map and the values are made accessible using a key. 

Basic Syntax:

declare -A array=(["key"]="value" ["key"]="value" ["key"]="value")

Here declares an associative array named "array" with three key-value pairs.

Creating associative arrays

Declaring 

The associative arrays have to be declared with the keyword 'declare' with the -A option. This option is a must to ensure the array is associative. Without the -A option, an indexed array will get declared.

Example:

declare -A array
declare an associative array

We have used this example to create an empty array named "array". It will not have any entry or key-value pair. Its size will be zero as it has only been declared. It is a fresh array.

Initializing 

We can declare and add elements to the array during the creation itself.

Example:

declare -A array=(["Paris"]="France" ["Vienna"]="Austria" ["Oslo"]="Norway")
initialize an associative array

The keyword, mentioned inside the square brackets, is referred to as the key. Each key has a corresponding value. In this example, we have declared an associative array with three key-value pairs: Paris-France, Vienna-Austria and Olso-Norway. 

If we have a populated array, we can see how it has been initialized using the -p flag. When it will act on the above array, it will give the entire command of how we initialized it.

Example:

declare -p array

Adding elements to an existing array

We can keep on adding more elements to the associative array:

Example:

declare -A array=(["Paris"]="France" ["Vienna"]="Austria" ["Oslo"]="Norway")
array["Warsaw"]="Poland"
array["Helsinki"]="Finland"
adding elements to an associative array

We have initialized an associative array with three entries. Next, we are adding another entry to the map. After adding the key value pair of Warsaw-Poland, the entries in the array will be four. Similarly, we have added another Helsinki-Finland key-pair value. The array now holds five elements.

Appending elements 

Given an associative array, we can append one or more key value pairs using the += operator. 

Syntax:

array+=([key1]=value1 [key2]=value2 [keyN]=valueN)

Example:

#!/bin/bash
declare -A arr
arr[Paris]=France
arr[Vienna]=Austria
echo -n  "Current array  "
echo ${arr[*]}
arr+=([Olso]=Norway [Warsaw]=Poland)
echo -n  "After appending 2 more elements it becomes "
echo ${arr[*]}
appending elements to an associative array

We are declaring an associative array. Then we add the entries Paris-France and Vienna-Austria as two key-value pairs. When we print the array, we get to see its contents. Then using the += operator, we append two more elements to the array. Finally, when we print the array after this, we get to see that now the array holds 4 entries.

Creating on the fly

We cannot create an associative array on the fly in Bash. We have to use the declare built-in command with "-A" explicitly. We can rely on the += operator which makes it possible to append one or more key-value pairs to the associative Bash array.

Example:

#!/bin/bash
declare -A arr
arr[Paris]=France
arr[Vienna]=Austria
arr+=([Olso]=Norway [Warsaw]=Poland)
echo ${arr[*]}

Accessing the Associative Array

Printing the array entries of the map is pretty straight forward. To refer to all the members of the array, we use the @ symbol. The use of the ∗ symbol as an index also gives the same output. The array, present inside the ${} construct, gets subjected to the parameter expansion.

Keys

We can get the list of keys alone by prefixing the "!" symbol with the array.

Example:

declare -A arr=(["Paris"]="France" ["Vienna"]="Austria" ["Oslo"]="Norway")
echo ${!arr[@]}
get the list of keys

Values

We can get the list the values of an associative array like we would do for any Bash array using the "@" symbol

Example:

declare -A arr=(["Paris"]="France" ["Vienna"]="Austria" ["Oslo"]="Norway")
echo ${arr[@]}
echo ${arr["Olso"]}
get the list the values

In this example, we are getting the entire list of values by placing the "@" symbol between the two square brackets. If we place the key there, we will get the corresponding value present in the map. In our case, arr["Olso"] will echo Norway on the screen.

Key-Value pairs

We can iterate over an associative array using loops to fetch the key-value pair.

Example:

#!/bin/bash
declare -A arr=(["Paris"]="France" ["Vienna"]="Austria" ["Oslo"]="Norway")
for i in ${!arr[@]}
    do
        echo $i:${arr[$i]}		#key:value 
    done
associative array using loops

There is no particular order in the output. It differs from the order of initialization. 

In index based arrays, we used ${#arr[@]} to retrieve the number of elements in the array. Index values are actually the keys in the map. Associative arrays return keys rather than indexes. Therefore, this incremental looping is not apt for maps. 

Delete operations

In Bash, we can either delete the entire array in one go or remove a particular element. We can also put this inside a loop to delete elements one by one or as per the situation.

Remove elements from the array

To remove an element from the array, we use the unset command. Unsetting a variable instructs Bash to discard the variable from the list of variables for tracking. We cannot access the stored value in the variable once it is unset. To unset, we need to provide the key within the square brackets.

Syntax:

unset arrayname[key]

Example:

unset array[Vienna]

Delete the entire array

We used the unset command to remove an element from the array. The same way we can destroy the complete array.

Example

unset arr

Clear the entire array

We might also want to clear the contents of the complete array. This will empty the array. To achieve this we just need to re-declare the array again. All the previously available information in the array gets cleared. 

Example:

declare -A arr=()

Example: A two-dimensional associative array

We have understood how associative arrays work. Now, let us look at a real-world problem. In this, we will implement 2D arrays. Arrays are collections of items. A 2D array is formed when these items are arrays as well. In 2D arrays, the elements can be identified by their positions. They act as coordinates. 

Bash only supports one-dimensional numerically indexed arrays as well as associative arrays. However, we can still implement them as follows:

Example:

#!/bin/bash
echo "------Associative array------"
declare -A arrA=([0,0]=Mercury [0,1]=Venus [1,0]=Earth [1,1]=Mars)
echo "${arrA[@]}"
for i in "${!arrA[@]}"
do 
    echo "$i -> ${arrA[$i]}"
done
implement 2D arrays

Since Bash doesn’t support 2D arrays, we can still implement them using the concept of 2D arrays and the other utilities Bash has on offer. For 2D associative arrays, the indices used are simply strings acting as keys. We can generate the keys in a loop.

Conclusion

  • Bash arrays are of two types- associative and indexed.
  • We have multiple ways of declaring and initializing an associative array.
  • Using the unset command, we can delete the elements as well as the entire associative array.
  • Bash doesn’t support 2D arrays but we have learned how we can implement the same.
SHARE

Comments

Please add comments below to provide the author your ideas, appreciation and feedback.

Leave a Reply

Leave a Comment