BASH Programming

Associative Arrays in Shell Scripts – Bash

Associative arrays are an essential data structure in programming languages that allow you to store key-value pairs. Bash, the most widely used shell in the Linux operating system, also supports associative arrays. This article will explore what associative arrays are in shell scripts, and how they can be used in Bash.

Associative Arrays in Shell Scripts

In Bash, an associative array is a collection of key-value pairs, where each key is unique, and each value can be accessed using its corresponding key. To create an associative array in Bash, you need to use the following syntax:

declare -A <array-name>

The declare command is used to define the variable <array-name> as an associative array, and the -A option is used to specify that the array is associative. To add an element to an associative array in Bash, you need to use the following syntax:

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

Here [key] is the key of the element, and <value> is the value associated with the key, here is an example of how to create and add elements to an associative array in Bash:

declare -A cars

cars["BMW"]="M5"

cars["VOLVO"]="X70"

cars["LEXUS"]="LX470"

Here, I have created an associative array named cars with three elements, each containing the respective car model of the corresponding manufacturer. As an example of how to get the value of an element in an associative array in Bash, here is how to retrieve the key of an element in an associative array:

associative-arrays-shell-scripts-bash#!bin/bash

declare -A cars

cars["BMW"]="M5"

cars["VOLVO"]="X70"

cars["LEXUS"]="LX470"

echo ${cars["LEXUS"]}

Here,I have used the key LEXUS to access the value LX470 associated with it, below is the output of the respective script:

A for loop can be used to repeatedly iterate through all the keys in an associative array. Here is an example in Bash showing how to do this:

associative-arrays-shell-scripts-bash#!bin/bash

declare -A cars

cars["BMW"]="M5"

cars["VOLVO"]="X70"

cars["LEXUS"]="LX470"

 

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

do

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

done

Here I have used the ${!cars[@]} syntax to get all the keys in the associative array and then used a for loop to iterate over all the keys and printed the corresponding values:

Conclusion

Associative arrays are a powerful data structure that allow you to store key-value pairs in Bash. You can create an associative array using the declare -A syntax, add elements to it using the array[key]=value syntax, and access the elements using their corresponding keys. Associative arrays can be useful for organizing and manipulating data in your Bash scripts.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.