Managing Indexed and Associative Arrays in Bash Scripts

Bash provides two primary data structures for handling collections of values: indexed arrays and associative arrays. Both are essential for organizing script parameters, configuration data, and iterative processing tasks.

Indexed Arrays

Indexed arrays store ordered elements accessible via zero-based integer indices. They are ideal for sequential data processing.

Declaration and Initialization

Arrays can be initialized inline using parentheses. Elements are separated by whitespace.

network_interfaces=(eth0 wlan0 lo docker0)

Element Retrieval

Access a specific item by referencing its numerical index within curly braces.

echo "${network_interfaces[1]}"  # Outputs: wlan0

Determining Array Size

The total number of elements is retrieved using the # prefix combined with the @ or * subscript.

interface_count=${#network_interfaces[@]}
echo "Total interfaces: $interface_count"

Iteration Patterns

Standard iteration loops through values directly. Quoting the expansion prevents word-splitting issues with elements containing spaces.

for iface in "${network_interfaces[@]}"; do
    echo "Checking status of $iface..."
done

For index-aware traversal, a C-style loop provides direct control over the counter variable.

total=${#network_interfaces[@]}
for (( idx=0; idx<total; idx++ )); do
    printf "Index %d maps to %s\n" "$idx" "${network_interfaces[$idx]}"
done

Associative Arrays

Associative arrays (often called dictionaries or hash maps) map arbitrary string keys to values. Bash requires explicit declaration before usage.

Declaration and Population

Use declare -A to initialize the strutcure, then assign key-value pairs individually or in bulk.

declare -A service_config
service_config[database_host]="192.168.1.50"
service_config[database_port]=5432
service_config[env]="production"

Value Lookup

Retrivee data by specifying the exact string key.

target_host="${service_config[database_host]}"
echo "Connecting to $target_host"

Extracting Keys and Values

The ! operator extracts all defined keys, while omitting it returns all stored values.

echo "Defined parameters: ${!service_config[@]}"
echo "Current settings: ${service_config[@]}"

Key-Value Traversal

Looping through an associative array typically involves iterating over the keys and performing lookups inside the loop body.

for param_key in "${!service_config[@]}"; do
    param_value="${service_config[$param_key]}"
    echo "Config [$param_key] = $param_value"
done

Tags: bash shell-scripting Arrays associative-arrays Linux

Posted on Mon, 28 Sep 2026 16:44:52 +0000 by MikeNye