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.
Code
#!/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 -rnReport a problem with this exampleOpens a pre-filled issue on GitHub.