Today I learned that bash has hashmaps (2024)
Bash has supported associative arrays (often called hashmaps) since version 4, a feature many users still discover by accident and view as both powerful and hazardous. Commenters highlight portability problems (notably macOS’s ancient Bash), surprising scoping and error-handling behaviors, and performance quirks, arguing that needing such structures is often a sign to switch to a higher-level language like Python or Go. Others counter that, used carefully and with attention to the manual, Bash’s arrays and piping model remain an efficient glue for composing Unix tools, as long as scripts stay within a certain complexity range.
Feature: Bash associative arrays (“hashmaps”)
- Bash has associative arrays via
declare -A, enabling key–value lookups. - Some find the syntax ugly or non-intuitive; others note it’s no worse than many mainstream languages.
- Keys can be listed with
${!map[@]}; behavior differs between bash and zsh, so scripts should pin the shebang to bash if using this.
Portability and macOS limitations
- macOS ships an ancient Bash 3.2 (due to GPL licensing), which lacks associative arrays; newer Bash from Homebrew supports them.
- This hurts portability across Linux/macos if you rely on associative arrays. Some prefer zsh (included on macOS) or stick to POSIX sh.
Pitfalls, scope, and reliability
- Associative arrays interact badly with Bash scoping and references:
localvariables have dynamic scope (visible to child functions), which surprises many.- Passing associative arrays “by value” doesn’t work; “by reference” requires
local -nand is fragile.
- There are reports of historical memory leaks with associative arrays in long-running scripts on older distros.
- Some argue that needing associative arrays is a sign the script is too complex and should move to Python, Go, etc.
Performance and implementation debate
- One comment claims lookups are linear-time and “slow AF”, implying they are not real hashmaps.
- Others argue “hashmap” is being used loosely: associative array is the abstraction; hash map is one possible implementation.
- There’s disagreement over whether it’s appropriate to call Bash’s structure a hashmap at all.
Shell vs. other languages and tools
- Several people like Bash for small glue scripts, pipelines, and text processing; they recommend other languages for heavy logic, data structures, and error handling.
- Others report writing very large, long-lived Bash systems successfully, emphasizing its ubiquity and speed.
Documentation, learning, and shell evolution
- Reading the Bash manual or release notes regularly surfaces features like arrays and obscure options.
- Some find the 80+ page man page daunting, preferring example-driven “cheat sheets”.
- Discussion touches on alternative shells (fish, nushell, PowerShell) and on whether Unix tools should output structured data (e.g., JSON) versus plain text.