Associative Arrays in Bash

Associative Arrays in Bash

On this page

Arrays are essential in Bash scripting for managing multiple related data items under one variable name. While indexed arrays use numerical indices, Bash also supports associative arrays, where each element is associated with a string key rather than a number. This makes associative arrays perfect for storing data pairs, like user information, configuration settings, or any other scenario where string-based keys provide more clarity than numbers.

In this article, we'll dive into associative arrays, exploring how to declare, manipulate, and use them effectively in your Bash scripts.

Declaring Associative Arrays

To declare an associative array in Bash, use the declare -A syntax. This setup is required for Bash to recognize the array as associative, enabling you to use string-based keys.

Associative Array Assignment

Once you have declared your associative array, you can assign key-value pairs to it. Bash provides two main ways to assign values to associative arrays: Key-by-Key Assignment and Compound Assignment.

Key-by-Key Associative Array Assignment

You can assign individual key-value pairs directly to an associative array. This method is useful when you need to add elements to the array one at a time.

declare -A person

person[name]="Jay"
person[age]=22
person[eye_color]="blue"

In this example, each element is added by specifying a key and assigning it a value.

Compound Associative Array Assignment

Bash supports a convenient syntax for mass-assigning multiple key-value pairs at once. With compound assignment, you can populate an associative array in a single line, listing each key-value pair within parentheses.

declare -A person # this line is required
# Quotes can be omitted for keys, as with "age"
person=(["name"]="Jay" [age]=22 ["eye_color"]="blue")

This approach is useful when initializing an array with multiple values at once.

Accessing and Manipulating Elements in Associative Arrays

To retrieve a specific value, use the syntax ${person[key]}, where key is the string key you assigned.

echo "${person[name]}"       # Output: Jay
echo "${person[eye_color]}"  # Output: blue

You can also retrieve all values at once by using ${person[@]} or ${person[*]}:

echo "${person[@]}"   # Output: Jay 22 blue
echo "${person[*]}"   # Output: Jay 22 blue

Both ${person[@]} and ${person[*]} return all values stored in the associative array.

Working with Keys in Associative Arrays

To access all keys in the array, use ${!person[@]}. This syntax returns all keys defined in the associative array, which is helpful for iterating over key-value pairs.

echo "${!person[@]}"   # Output: name age eye_color

To check the number of elements in the array, you can use ${#person[@]}:

Modifying and Deleting Elements in Associative Arrays

Updating a value is as simple as reassigning a new value to an existing key:

person[eye_color]="green"
echo "${person[eye_color]}"  # Output: green

To delete a specific key-value pair, use the unset command with the key specified. This removes the specified key and its associated value from the array.

Looping Through an Associative Array

One common way to loop through an associative array is by iterating over its keys. This allows you to access both keys and values within the loop.

for key in "${!person[@]}"; do
    echo "$key: ${person[$key]}"
done

This loop will print each key-value pair, giving you a structured view of the data stored within it.

Summing up

Associative arrays in Bash offer a flexible way to store and manage data with string-based keys. By mastering associative arrays, you can add a new layer of functionality to your scripts, making them more powerful and adaptable. With the ability to access, update, and iterate over key-value pairs, associative arrays are a valuable asset for handling structured data in Bash scripting.

Subscribe to sysxplore newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox. It's free!
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!