Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readLinux
#Linux#Bash#Shell#Scripting
3D illustration of indexed array slots and key-value map tiles expanded by parameter substitution braces

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

bash
# 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
bash
# 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)
bash
# 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 prefix

Key Comparison Table

ExpansionOne element with a spaceResult family
"${arr[@]}"Preserved as one wordWord per element — the correct form
${arr[@]}Split on IFS and globbedWord splitting and pathname expansion
"${arr[*]}"Joined with the first character of IFSOne word total
${arr[*]}Joined, then split againJoined and re-split
"$*"Joined with IFSPositional parameters as one word
"$@"One word per parameterThe positional equivalent of "${arr[@]}"
OperatorUnsetEmptySet
${v:-x}xxvalue
${v-x}x(empty)value
${v:=x}assigns xassigns xvalue
${v:?msg}errorerrorvalue
${v:+x}(empty)(empty)x
NeedExpression
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 arrayprintf '%s\n' "${arr[@]}" | sort
Join with a commaIFS=,; echo "${arr[*]}"

Practical Edge Cases & Deep Dives

1. Quoting is the whole ballgame

bash
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 here

The 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

bash
set -u arr=() echo "${arr[@]}" # bash < 4.4: "arr[@]: unbound variable" echo "${arr[@]:-}" # safe on every version echo "${#arr[@]}" # 0, always safe

Treating 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:

bash
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 expanding

3. Reading input safely: read -a, mapfile, and IFS

bash
# 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"; done

while read in a pipeline runs in a subshell, so anything it assigns is lost:

bash
count=0 grep -c . file | read -r count # count stays 0 while IFS= read -r line; do ((count++)); done < file # redirection, not a pipe

Process 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

bash
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

bash
# 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 spaces

A 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
$ bash --version | head -1 GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin) $ declare -A m bash: declare: -A: invalid option

Bash 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:

bash
if (( BASH_VERSINFO[0] < 4 )); then echo "bash 4+ required" >&2; exit 1 fi

Common Runtime & Configuration Mistakes

SymptomCauseFix
Elements split at spacesUnquoted ${arr[@]}"${arr[@]}"
Array elements glob to filenamesUnquoted expansionQuote; 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 thingGlob interpretation of bracketsunset 'arr[1]'
declare -A: invalid optionbash 3.2 (macOS default)Install bash 4+, or use case/files
unbound variable on an empty arrayset -u with bash < 4.4"${arr[@]:-}"
Loop counter resets to 0while read in a pipeline subshellRedirect or process substitution
Newlines lost from mapfile-t missing (each line keeps \n)mapfile -t
Filenames with spaces break forSplitting ls or $(find)find -print0 + mapfile -d ''
${file##*.} returns the whole nameNo dot in the namecase guard
${var: -3} errorsSpace before - omitted${var: -3} or ${var:(-3)}
Associative keys come out unorderedHash order is unspecifiedSort the keys
${!prefix@} emptyNo matching variable namesCheck 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 tools

Small utilities that fit Linux work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Linux guides

More in Linux

All Linux guides

The guides filed next to this one in Linux, in library order.