BudiBadu Logo
Samplebadu

Bash by Example: Associative Arrays

Bash 5.0+

Using key-value pairs (dictionaries/maps) in Bash 4.0+ through associative arrays, understanding the mandatory declare -A syntax for proper initialization, accessing values by string keys instead of numeric indices, iterating over keys and values, and implementing lookup tables for configuration management.

Code

#!/bin/bash

# Declare associative array (REQUIRED)
declare -A colors

# Assign values
colors[red]="#FF0000"
colors[green]="#00FF00"
colors[blue]="#0000FF"

# Access by key
echo "Red hex: ${colors[red]}"

# List all keys (!)
echo "Keys: ${!colors[@]}"

# List all values
echo "Values: ${colors[@]}"

# Iterate over keys
for key in "${!colors[@]}"; do
    echo "$key -> ${colors[$key]}"
done

Explanation

Bash 4.0 introduced associative arrays, also known as maps or dictionaries. Unlike standard indexed arrays that use integers, associative arrays use strings as keys. This allows you to create lookup tables and manage structured data more effectively directly within your scripts.

A critical requirement for associative arrays is explicit declaration using declare -A. If you skip this step, Bash will treat the variable as a standard indexed array, and keys like "red" or "blue" will likely evaluate to index 0, causing data overwrites and unexpected behavior.

Accessing data in associative arrays is similar to indexed arrays but uses the string key. To retrieve a list of all keys in the map, you use the exclamation mark prefix, like ${!array[@]}. Note that associative arrays are unordered; iterating over them does not guarantee any specific sequence.

Code Breakdown

4
declare -A colors is mandatory. It tells Bash to treat "colors" as a map. Without this, colors[red] would be interpreted as colors[0].
7-9
Assigning values using string keys. The keys "red", "green", and "blue" are mapped to their respective hex codes.
15
${!colors[@]} expands to the list of keys. The ! is the special operator for "indirection" or "keys" in this context.
21
Iterating over the keys allows you to access both the key and the value (${colors[$key]}) inside the loop.