Associative Arrays in Shell Scripts


Associative arrays are vital in programming languages for storing key-value pairs. They are also supported in Bash, the popular Linux shell. This article delves into shell script associative arrays and their usage in Bash. For illustration, I have used one of the most widely used Linux Distros that is Ubuntu 22.04

Associative Arrays in Shell Scripts

An associative array in Bash is a special group of key-value pairs that can be retrieved by their corresponding keys. To form an associative array in Bash, utilize the subsequent syntax:

declare -A <name-of-array>

To define a variable <name-of-array> as an associative array in Bash, utilize the declare command with the -A option. To add an element to this associative array, employ the following syntax:

<array-name>[key]=<value>

In Bash, the key-value pair in an associative array is defined by [key] as the key and <value> as the corresponding value. Here’s an example demonstrating how to create an associative array and add elements to it:

declare -A Phones

Phones["APPLE"]="12 Pro"

Phones["LG"]="Q7"

Phones["One_Plus"]="8 Pro"

echo ${Phones["LG"]}

In this example, an associative array named “Phones” has been created with three elements, each representing the phone model of a specific manufacturer. To retrieve the key of an element in an associative array in Bash, you can use the following syntax:

#!bin/bash

declare -A Phones

Phones["APPLE"]="12 Pro"

Phones["LG"]="Q7"

Phones["One_Plus"]="8 Pro"

echo ${Phones["LG"]}

In this case, the key “LG” is utilized to retrieve the associated value “Q7” from the associative array. Here is the resulting output from the script:

To iterate through all the keys in an associative array using a for loop in Bash, consider the following example:

#!bin/bash

declare -A Phones

Phones["APPLE"]="12 Pro"

Phones["LG"]="Q7"

Phones["One_Plus"]="8 Pro"

for key in "${!Phones[@]}"

do

 echo "The model of ${key} is ${Phones[$key]}"

done

In the given example, the ${!Phones[@]} syntax is employed to retrieve all the keys in the associative array. Subsequently, a for loop is utilized to iterate over these keys, and the corresponding values are printed. Here is the code snippet illustrating this:

Conclusion

Associative arrays in Bash provide a robust data structure for storing key-value pairs. By using the declare -A syntax, you can create an associative array. Elements can be added to it using the array[key]=value syntax, and you can access the elements using their respective keys. Leveraging associative arrays can greatly assist in organizing and manipulating data within your Bash scripts.

Print Friendly, PDF & Email
Categories