Bash Associative Arrays



Bash Associative Arrays

In Bash scripting, associative arrays are used to store key-value pairs. Understanding how to define, manipulate, and perform operations on associative arrays is crucial for effective shell scripting.


Defining Associative Arrays

Associative arrays in Bash can be defined using the declare -A syntax.

#!/bin/bash

 # Define an associative array
declare -A assoc_array
assoc_array=( ["name"]="Alice" ["age"]=25 ["city"]="New York" )

In this example, assoc_array is defined with three key-value pairs: 'name' is 'Alice', 'age' is 25, and 'city' is 'New York'.


Accessing Elements

Elements in an associative array can be accessed using their keys.

#!/bin/bash

 # Define an associative array
declare -A assoc_array
assoc_array=( ["name"]="Alice" ["age"]=25 ["city"]="New York" )
# Access elements in the associative array
echo "Name: ${assoc_array["name"]}"
echo "Age: ${assoc_array["age"]}"
echo "City: ${assoc_array["city"]}"

In this example, the values associated with the keys 'name', 'age', and 'city' are accessed and printed.

Accessing elements in associative arrays in Bash

Adding and Updating Elements

Elements can be added to or updated in an associative array by assigning values to new or existing keys.

#!/bin/bash

 # Define an associative array
declare -A assoc_array
assoc_array=( ["name"]="Alice" ["age"]=25 ["city"]="New York" )
# Add or update elements
assoc_array["country"]="USA"
assoc_array["city"]="Los Angeles"

echo "Country: ${assoc_array["country"]}"
echo "Updated City: ${assoc_array["city"]}"

In this example, a new key-value pair 'country' is added, and the value of the key 'city' is updated.

Adding and updating elements in associative arrays in Bash

Iterating Over Associative Arrays

Associative array elements can be iterated over using a for loop to access keys and values.

#!/bin/bash

 # Define an associative array
declare -A assoc_array
assoc_array=( ["name"]="Alice" ["age"]=25 ["city"]="New York" )
# Iterate over associative array elements
for key in "${!assoc_array[@]}"; do
    echo "$key: ${assoc_array[$key]}"
done

In this example, a for loop is used to iterate over each key in assoc_array, and the key-value pairs are printed.

Iterating over associative arrays in Bash

Conclusion

Working with associative arrays in Bash is essential for managing key-value pairs in shell scripts. Understanding how to define, access, add, update, remove, iterate over, and check keys in associative arrays can help you manage and manipulate data more effectively in your scripts.