Associative Arrays for Key-Value Data

Uses Bash associative arrays (hash maps) for key-value storage, iteration, lookup, and data aggregation with practical configuration and counting examples.

BashConfig Management

Code

snippet
#!/usr/bin/env bash
set -euo pipefail

# Declare associative array
declare -A config

# Assign key-value pairs
config[host]="localhost"
config[port]="8080"
config[debug]="true"
config[log_file]="/var/log/app.log"

# Access values
echo "Host: ${config[host]}"
echo "Port: ${config[port]}"

# Check if key exists
if [[ -v config[debug] ]]; then
    echo "Debug mode: ${config[debug]}"
fi

# Iterate over keys
echo "=== Configuration ==="
for key in "${!config[@]}"; do
    printf "  %-10s = %s\n" "$key" "${config[$key]}"
done

# Count entries
echo "Total config items: ${#config[@]}"

# Build from key-value pairs
declare -A env_vars
while IFS="=" read -r key value; do
    [[ -z "$key" || "$key" == \#* ]] && continue
    env_vars["$key"]="$value"
done << 'EOF'
NODE_ENV=production
PORT=3000
DATABASE_URL=postgres://localhost/mydb
SECRET_KEY=abc123
EOF

echo "=== Environment ==="
for key in "${!env_vars[@]}"; do
    echo "  $key=${env_vars[$key]}"
done

# Word frequency counter
declare -A word_count
for word in $(echo "the quick brown fox the lazy dog the fox runs"); do
    (( word_count["$word"]++ ))
done

echo "=== Word Counts ==="
for word in "${!word_count[@]}"; do
    printf "  %-10s : %d\n" "$word" "${word_count[$word]}"
done | sort -t: -k2 -rn

Associative arrays (declare -A) store key-value pairs (Bash 4+). ${!arr[@]} iterates keys, ${arr[@]} iterates values, ${#arr[@]} counts entries, [[ -v arr[key] ]] checks key existence. They are ideal for configuration, counting, caching, and lookups. Keys can be any string, including spaces. Always quote keys to handle special characters.

Interactive Tools for This Topic