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 -rnAssociative 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
Report a problem with this exampleOpens a pre-filled issue on GitHub.