功能说明
示例用 declare -A 创建关联数组(哈希表),存储主机、端口、调试开关等配置;再从 heredoc 中的 KEY=VALUE 文本构建环境变量映射;最后统计一句话中每个单词出现的次数。适用于配置管理、查找表和简单聚合等场景。
关键代码
declare -A config声明关联数组,之后可用config[host]="localhost"这样的字符串键赋值。${config[host]}按键取值,${#config[@]}返回键值对数量,${!config[@]}展开所有键。[[ -v config[debug] ]]判断键是否存在,避免读取未定义键。- 读取环境变量时使用
while IFS="=" read -r key value,并用[[ -z "$key" || "$key" == \#* ]] && continue跳过空行和注释行。 - 词频统计通过
(( word_count["$word"]++ ))累加,输出时用sort -t: -k2 -rn按次数倒序排列。
使用注意
关联数组需要 Bash 4 及以上版本,macOS 自带的 Bash 3.2 不支持。遍历顺序并不保证稳定,需要有序输出时应显式排序。键可能包含空格或特殊字符,赋值和读取都应加引号;set -u 下读取不存在的键会报错,先用 -v 检查更稳妥。
验证方式
保存为 associative-arrays.sh 后执行,确认配置区打印 4 项、环境区打印 4 个键值对,词频统计中 the 出现 3 次并排在首位。可在 Bash 4+ 环境中用 bash --version 先确认版本。
代码示例
#!/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