用关联数组做键值查找

在脚本里用映射替代冗长的 if 链。

macOSBash 脚本Shell脚本低风险
运行 declare -A sizes=([small]=1 [large]=3),再读取 ${sizes[large]}。

01命令

命令
$ declare -A sizes=([small]=1 [large]=3); echo "${sizes[large]}"

02作用说明

关联数组把一串条件判断变成直接查表,让脚本中的配置表简短易读。需要 bash 4+,macOS 用户可能要用 Homebrew bash;这是纯脚本能力,图形界面没有对应物。

03风险

风险低风险
使用条件macOS default zsh/bash (bash 3.2+; some features need bash 4+ via Homebrew)
系统兼容性macOS with bash 3.2+ (GNU bash 4+ via Homebrew for advanced features)
!注意: macOS 自带 bash 3.2,不支持关联数组;请安装 bash 4+ 或改用 zsh 的 typeset -A。

04撤销

✓无需撤销——该命令不会改变持久状态。

05来源

最后验证: 2026-10-13 · 分类: 开发者