Bash Indexed Arrays, Associative Maps, and Parameter Expansion
Quoting decides whether an array stays a list, and the expansion operators replace most external text tools. Includes set -u, mapfile, namerefs, and the bash 3.2 differences that break scripts on macOS.

Quick Summary
Bash has two array types: indexed arrays, keyed by integers, and associative arrays, keyed by strings and requiring declare -A before first use. Both are sparse, both expand to a list of words, and both behave differently depending on whether the expansion is quoted. "${arr[@]}" produces one word per element, preserving spaces and empty strings; ${arr[@]} and "${arr[*]}" produce something else, and those two differences cause most of the bugs people blame on bash.
Parameter expansion is the other half: ${var:-default}, ${var#prefix}, ${var%.*} (strip the extension), ${path##*/} (basename), ${name//pat/repl}, ${var:offset:length}, and the case modifiers ${var^^}/${var,,}. It runs inside the shell, so it costs no process, handles unset variables explicitly (:-, :=, :?, :+), and substitutes the place where a dozen sed/cut/basename calls would otherwise appear.
The reliable style for real scripts is declare -a/declare -A, always quoted "${arr[@]}" when iterating, ${!arr[@]} for keys and indices, and mapfile to read a file into an array without word-splitting surprises. This guide covers declaration, indexing, iteration in stable order, read/mapfile input, the full expansion operator table, nested substitution, and the set -u and bash-version traps that break otherwise correct scripts.
Basic Syntax & Core Signatures
# Indexed arrays
arr=(alpha "beta gamma" delta)
arr+=(epsilon) # append one element
arr[10]=far # sparse: index 10, no element at 5..9
declare -a declared=(1 2 3)
read -r -a words <<< "one two three"
# Read and length
echo "${arr[0]}" # first element
echo "${arr[-1]}" # last element (bash 4.3+)
echo "${#arr[@]}" # number of elements
echo "${#arr[1]}" # length of element 1
echo "${!arr[@]}" # all indices, in unspecified order
echo "${arr[@]:1:2}" # slice: 2 elements starting at index 1
# Iterate
for item in "${arr[@]}"; do printf '%s\n' "$item"; done
for i in "${!arr[@]}"; do printf '%s=%s\n' "$i" "${arr[$i]}"; done
# Delete
unset 'arr[1]' # one element (quote the brackets!)
unset arr # the whole array
# Assign into a slot / read one line per element
mapfile -t lines < file.txt # -t strips trailing newlines
mapfile -t -n 5 head5 < file.txt # first 5 lines# Associative arrays (bash 4.0+; not in macOS's default 3.2)
declare -A config
config[host]="db.internal"
config[port]=5432
config["log level"]="debug"
for key in "${!config[@]}"; do printf '%s=%s\n' "$key" "${config[$key]}"; done
unset 'config[port]'
[[ -v config[host] ]] && echo "host is set" # bash 4.2+
# Stable order: sort the keys, never rely on hash order
while IFS= read -r k; do printf '%s=%s\n' "$k" "${config[$k]}"; done \
< <(printf '%s\n' "${!config[@]}" | sort)# Parameter expansion: defaults, errors, alternatives
${var:-default} # value, or default if unset OR empty
${var-default} # value, or default if unset only
${var:=default} # assign the default to var as well
${var:?message} # abort with message if unset/empty
${var:+alt} # alt if var is set and non-empty
${#var} # length in characters
# Substrings
${var:2} # from offset 2 to the end
${var:2:5} # 5 characters from offset 2
${var: -3} # last 3 characters (space before '-' is required)
# Trimming
${path#*/} # remove shortest prefix matching */
${path##*/} # remove longest prefix: basename
${file%.*} # remove shortest suffix: strip extension
${file%%.*} # remove longest suffix
${name#app-} # strip a literal prefix
# Replacement
${v/foo/bar} # first match
${v//foo/bar} # all matches
${v/#foo/bar} # only at the start
${v/%foo/bar} # only at the end
${v//[[:space:]]/} # strip all whitespace
# Case and quoting
${v^^} ${v,,} # upper / lower (bash 4.0+)
${v@Q} # re-quotable form, for eval or logging
${v@P} # expand as a prompt string
# Indirection
name=host; host=db.internal; echo "${!name}" # db.internal
${!prefix@} # names of variables starting with prefixKey Comparison Table
| Expansion | One element with a space | Result family |
|---|---|---|
"${arr[@]}" | Preserved as one word | Word per element — the correct form |
${arr[@]} | Split on IFS and globbed | Word splitting and pathname expansion |
"${arr[*]}" | Joined with the first character of IFS | One word total |
${arr[*]} | Joined, then split again | Joined and re-split |
"$*" | Joined with IFS | Positional parameters as one word |
"$@" | One word per parameter | The positional equivalent of "${arr[@]}" |
| Operator | Unset | Empty | Set |
|---|---|---|---|
${v:-x} | x | x | value |
${v-x} | x | (empty) | value |
${v:=x} | assigns x | assigns x | value |
${v:?msg} | error | error | value |
${v:+x} | (empty) | (empty) | x |
| Need | Expression |
|---|---|
| Filename without directory | ${path##*/} |
| Directory of a path | ${path%/*} |
| Extension | ${file##*.} (wrong for names with no dot — guard it) |
| Name without extension | ${file%.*} |
| Element count | ${#arr[@]} |
| Keys / indices | ${!arr[@]} (assoc: keys, indexed: indices) |
| Sort lines from an array | printf '%s\n' "${arr[@]}" | sort |
| Join with a comma | IFS=,; echo "${arr[*]}" |
Practical Edge Cases & Deep Dives
1. Quoting is the whole ballgame
files=("a b.txt" "c.txt" "")
for f in "${files[@]}"; do printf '[%s]\n' "$f"; done
# [a b.txt]
# [c.txt]
# []
for f in ${files[@]}; do printf '[%s]\n' "$f"; done
# [a] <- split
# [b.txt]
# [c.txt]
for f in *; do :; done # unquoted ${files[@]} also globs, so "*" expands hereThe unquoted form performs word splitting on IFS and then pathname expansion, so an element containing *, a space, or a newline turns into several arguments or a filename match. Every array loop in production code should read "${arr[@]}", and every variable passed to a command should be quoted unless the script deliberately wants splitting — find ... -exec and xargs -0 are the two places where lists of filenames should never go through an unquoted expansion at all.
2. set -u, empty arrays, and the ${arr[@]} trap
set -u
arr=()
echo "${arr[@]}" # bash < 4.4: "arr[@]: unbound variable"
echo "${arr[@]:-}" # safe on every version
echo "${#arr[@]}" # 0, always safeTreating an empty array as unset was a bug fixed in bash 4.4, but scripts still meet bash 3.2 on macOS and older appliances. The portable idiom is "${arr[@]:-}" or ${#arr[@]} -eq 0 checks before expansion. The same class of problem appears with associative arrays and set -u:
declare -A m
echo "${m[$key]}" # unbound variable under set -u if the key is absent
echo "${m[$key]:-}" # empty instead
[[ -v "m[$key]" ]] && echo present # bash 4.2+, test without expanding3. Reading input safely: read -a, mapfile, and IFS
# CSV-ish line into fields, without a subshell
IFS=, read -r -a fields <<< "alice,42,admin"
printf '%s\n' "${fields[1]}" # 42
# A whole file, one line per element, no globbing or splitting
mapfile -t lines < /etc/hosts
printf '%s\n' "${lines[@]}" | wc -l
# NUL-separated filenames: the only safe form
mapfile -t -d '' files < <(find /srv/app -maxdepth 1 -type f -print0)
for f in "${files[@]}"; do echo "$f"; donewhile read in a pipeline runs in a subshell, so anything it assigns is lost:
count=0
grep -c . file | read -r count # count stays 0
while IFS= read -r line; do ((count++)); done < file # redirection, not a pipeProcess substitution (< <(...)) keeps the loop in the current shell, which is why it is the standard fix for the "my counter never increments" bug.
4. Pattern trimming versus regex: which one to reach for
path=/srv/app/releases/2026.11.15/app.tar.gz
echo "${path##*/}" # app.tar.gz (basename)
echo "${path%/*}" # /srv/app/releases/2026.11.15
echo "${path##*.}" # gz
echo "${path#*.}" # tar.gz (everything after the first dot)
echo "${path%.tar.gz}" # .../app
# Guard the no-extension case: ${file##*.} returns the whole name unchanged
case $name in
*.*) base=${name%.*}; ext=${name##*.} ;;
*) base=$name; ext="" ;;
esac# and % take glob patterns, not regular expressions; , makes the match case-insensitive in bash 4 (${v,pattern}), and bracket expressions such as [0-9] work. For anything with alternation or capture groups, [[ $v =~ $re ]] with BASH_REMATCH is the in-shell tool, and sed is the last resort rather than the first.
5. Indirect references, namerefs, and passing arrays around
# Indirection by name
target=PRIMARY_HOST
PRIMARY_HOST=db1.internal
echo "${!target}" # db1.internal
# Nameref (bash 4.3+): a function can modify the caller's array
fill() { local -n out=$1; out=(a b c); }
declare -a got; fill got; echo "${got[1]}" # b
# Passing arrays: expand at the call site, collect with "$@"
sum() { local total=0 n; for n in "$@"; do ((total+=n)); done; echo "$total"; }
nums=(1 2 3 4); sum "${nums[@]}" # 10
# Never assign an array to a scalar and expect the elements
flat="${nums[@]}" # a single string with spacesA nameref makes the "return an array from a function" problem disappear without eval; the older trick of printing elements and re-reading them through a command substitution loses empty elements and trailing newlines.
6. Bash version differences that break scripts
$ bash --version | head -1
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin)
$ declare -A m
bash: declare: -A: invalid optionBash 3.2, still the default /bin/bash on macOS, lacks associative arrays, mapfile, ${v^^}, ${v@Q}, [[ -v ]], negative indices, and local -n. A script that runs in a container and fails on a developer's laptop is usually one of those. The portable alternatives are case instead of associative arrays, tr for case conversion, printf -v instead of indirect assignment, and #!/usr/bin/env bash plus a version check at the top when the feature is essential:
if (( BASH_VERSINFO[0] < 4 )); then
echo "bash 4+ required" >&2; exit 1
fiCommon Runtime & Configuration Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Elements split at spaces | Unquoted ${arr[@]} | "${arr[@]}" |
| Array elements glob to filenames | Unquoted expansion | Quote; use set -f only deliberately |
| Only the first element used | $arr instead of ${arr[@]} | Expand the whole array |
unset arr[1] errors or unsets the wrong thing | Glob interpretation of brackets | unset 'arr[1]' |
declare -A: invalid option | bash 3.2 (macOS default) | Install bash 4+, or use case/files |
unbound variable on an empty array | set -u with bash < 4.4 | "${arr[@]:-}" |
| Loop counter resets to 0 | while read in a pipeline subshell | Redirect or process substitution |
Newlines lost from mapfile | -t missing (each line keeps \n) | mapfile -t |
Filenames with spaces break for | Splitting ls or $(find) | find -print0 + mapfile -d '' |
${file##*.} returns the whole name | No dot in the name | case guard |
${var: -3} errors | Space before - omitted | ${var: -3} or ${var:(-3)} |
| Associative keys come out unordered | Hash order is unspecified | Sort the keys |
${!prefix@} empty | No matching variable names | Check the prefix spelling |
Arrays and parameter expansion replace most external text tools inside a script, and their one rule is that expansion happens after parsing: the quoting decides whether the result is one word or many, and the operators decide whether an unset variable is an error, a default, or an assignment. Scripts that quote every array expansion and use :-/:? deliberately read the same on bash 3.2 and bash 5, and fail loudly instead of silently operating on the wrong list of files.
Try matching browser tools
All toolsSmall utilities that fit Linux work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Linux guides
All Linux guidesParsing JSON and YAML in Shell Pipelines with jq and yq
jq is a filter language, not a pretty-printer. The operators that do the work, --arg versus string interpolation, in-place YAML edits, and how to tell which yq is installed before writing a command.
Linux Memory, Swap, the OOM Killer, vmstat, and sysctl Tuning
MemAvailable versus used, the vmstat columns that prove thrashing, how the OOM killer picks its victim, and the sysctl keys that belong in /etc/sysctl.d instead of a one-off command.
Linux Firewalls: ufw, iptables, and nftables Rules and Persistence
First-match ordering, stateful filtering, and persistence: the three ideas behind every Linux firewall. Plus why Docker-published ports ignore ufw and how DOCKER-USER closes them.
Linux Users, Groups, sudoers, and PAM Access Control
The four account files, the sudoers grammar with aliases and drop-ins, and the PAM stack where logins actually succeed or fail. Includes the flags that lock an account without disabling SSH keys.
More in Linux
All Linux guidesThe guides filed next to this one in Linux, in library order.