Associative arrays
An associative array maps nonempty string keys to string values, like a small lookup table. Declare it first with declare -A settings (Bash 4.0 or newer; tested here on 5.2). Assign using settings[theme]=dark and read using "${settings[theme]}". Keys may contain spaces; use a fixed quoted key in assignments, such as settings["daily report"]=ready. Distinguish an absent key from a key assigned an empty string using the parameter-expansion alternate-value form, shown below with a fixed key. Key iteration order is not a stable contract; for repeatable output iterate over an explicit list of known keys. Associative subscript evaluation is version-sensitive in some contexts: these examples intentionally use fixed trusted keys or known labels. Do not treat arbitrary external key text as executable syntax or assume quoting solves every historical subscript evaluation issue. Arrays are shell-local structures: export does not transmit a structured array through the normal environment; pass individual arguments or use a defined serialization format instead.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Lookup by string key
declare -A settings=([theme]=dark [mode]=test)printf '%s\n' "${settings[theme]}" "${settings[mode]}"Expected stdout:
darktestEach string key selects its own value.
Keep a key with spaces
declare -A statusstatus['daily report']=readystatus[backup]=pendingfor key in 'daily report' backup; do printf '%s=%s\n' "$key" "${status[$key]}"doneExpected stdout:
daily report=readybackup=pendingThe explicit list controls order; key values come from trusted constants.
Separate missing from empty
declare -A settings=([note]='')printf 'note=%s\nmissing=%s\n' "${settings[note]+present}" "${settings[missing]+present}"Expected stdout:
note=presentmissing=The + form tests assignment, not whether the value is nonempty.
Common mistakes
Do not omit declare -A when you intend string keys: an indexed array evaluates subscripts arithmetically. Do not rely on the order printed by associative key enumeration or use an empty key.
Practice
Create a lookup table with two fixed labels and a third key holding an empty string. Print two labels in a fixed order and distinguish the empty key value from a missing key.
Next: Build commands with arrays