Common Array Pitfalls
Bash arrays were added to a language that was built around plain strings, and many of their rough edges come from that history: an array name on its own still behaves like a string, expansions still split and glob unless quoted, and a missing declaration silently produces a different kind of array. Most array bugs do not produce an error message. The script keeps running with the wrong data. This lesson collects the traps that appeared across lessons 97 to 104, shows what each one looks like when it happens, and gives the form that works.
Each section has the same shape: the code that goes wrong, its real output, the reason, and the correct version.
Unquoted Expansions Split Elements Apart
names=("Ana Maria" "Bo")
printf '[%s]\n' ${names[@]}
[Ana]
[Maria]
[Bo]
Why: without quotes, the expanded elements go through word splitting and filename expansion (lessons 52 and 53), so Ana Maria becomes two words. An element such as *.log would also be replaced by matching file names.
Fix: always write "${names[@]}", with the quotes, wherever an array is expanded: in loops, in command arguments, in function calls and when copying.
"${arr[*]}" Joins Everything into One Word
for x in "${names[*]}"; do echo "[$x]"; done
[Ana Maria Bo]
Why: quoted [*] joins all elements into a single string separated by the first character of IFS (lesson 98). The loop ran once.
Fix: use [@] to keep elements separate. Use [*] only when one joined string is the goal, such as a message or a comma-separated line.
A Bare Name Means Element 0
echo "$names"
Ana Maria
Why: $names is the same as ${names[0]} (lesson 98). The same rule breaks copying:
arr=(10 20 30)
copy=$arr
declare -p copy
declare -- copy="10"
The assignment created a plain string holding element 0.
Fix: to read everything, use "${arr[@]}". To copy an array, build a new one from its elements:
copy=("${arr[@]}")
declare -p copy
declare -a copy=([0]="10" [1]="20" [2]="30")
Copying this way also renumbers a sparse array from 0. For associative arrays, copy key by key (lesson 102).
${#arr} Is Not the Element Count
echo "${#names}" "${#names[@]}"
9 2
Why: ${#names} is the length of element 0, Ana Maria, which has 9 characters (lesson 101).
Fix: count elements with ${#names[@]}.
+= Without Parentheses Appends Text
list=(a b)
list+=c
declare -p list
declare -a list=([0]="ac" [1]="b")
Why: list+=c is string concatenation on list, which means element 0 (lesson 99).
Fix: add elements with parentheses: list+=(c), or list+=("$value") for a variable.
Command Output Is Not an Array
out=$(printf 'one\ntwo three\n')
declare -p out
echo "count: ${#out[@]}"
declare -- out=$'one\ntwo three'
count: 1
Why: command substitution produces one string. Assigning it with = creates a plain variable, newlines and all.
Wrapping the substitution in parentheses creates an array, but through word splitting and globbing, which is rarely what is wanted. Run in a folder that contains a file named x y.log:
w=( $(printf 'one\ntwo three\n*.log\n') )
declare -p w
declare -a w=([0]="one" [1]="two" [2]="three" [3]="x y.log")
The line two three became two elements, and the line *.log was replaced by a file name.
Fix: read the output line by line with mapfile and process substitution (lesson 98):
mapfile -t ok < <(printf 'one\ntwo three\n*.log\n')
declare -p ok
declare -a ok=([0]="one" [1]="two three" [2]="*.log")
Each line becomes exactly one element, with no splitting or globbing.
Filling an Array Inside a Pipe
found=()
printf 'a\nb\n' | while read -r line; do found+=("$line"); done
echo "after pipe: ${#found[@]}"
after pipe: 0
Why: each part of a pipeline runs in a subshell (lesson 61). The loop filled a copy of found that disappeared when the pipeline ended. The same happens with printf ... | mapfile -t arr.
Fix: put the command in process substitution and redirect it into the loop or into mapfile: while ...; done < <(command) or mapfile -t arr < <(command). For a file, redirect the file itself: done < file.
Unquoted unset Can Be Treated as a Glob
touch m1
m=(zero one two)
unset m[1]
declare -p m
declare -a m=([0]="zero" [1]="one" [2]="two")
Why: m[1] is a valid glob pattern meaning "the letter m followed by the character 1". With a file named m1 in the current directory, the shell replaced the word with m1 before unset ran, so unset removed a variable named m1 instead of the element (lesson 99). The bug appears only in folders that happen to contain a matching file.
Fix: quote the element: unset 'm[1]'.
declare -a m=([0]="zero" [2]="two")
Counting Loops on Sparse Arrays
s=(a b c d)
unset 's[1]'
for (( i = 0; i < ${#s[@]}; i++ )); do printf '[%s]' "${s[i]}"; done; echo
[a][][c]
Why: after the unset, the array has three elements at indexes 0, 2 and 3. The loop visited indexes 0, 1 and 2, read nothing at the gap, and never reached d (lesson 100).
Fix: loop over the indexes that exist:
for i in "${!s[@]}"; do printf '[%s]' "${s[i]}"; done; echo
[a][c][d]
Related: count - 1 is not the last index of a sparse array. Use ${arr[-1]} for the last value (lesson 101).
Pattern Removal Leaves Empty Elements
fr=(apple banana cherry)
fr=("${fr[@]/banana}")
declare -p fr
echo "count ${#fr[@]}"
declare -a fr=([0]="apple" [1]="" [2]="cherry")
count 3
Why: ${fr[@]/banana} replaces the matching text inside each element with nothing. It changes values; it does not remove elements (lesson 99).
Fix: starting from the original array, build a new array that skips the unwanted values:
fr=(apple banana cherry)
keep=()
for f in "${fr[@]}"; do [[ $f != banana ]] && keep+=("$f"); done
declare -p keep
declare -a keep=([0]="apple" [1]="cherry")
or unset the element by its index.
Forgetting declare -A
age[ana]=31
age[bo]=25
echo "ana is ${age[ana]}"
declare -p age
ana is 25
declare -a age=([0]="25")
Why: without declare -A, Bash creates an indexed array and evaluates ana and bo as arithmetic. Both are unset variable names, so both mean index 0, and the second assignment overwrote the first (lesson 102).
Fix: declare every associative array first: declare -A age, or local -A age inside a function. If a script prints values that "belong" to another key, check the type with declare -p.
Words as Indexes of an Indexed Array
The same arithmetic rule surprises scripts that use a word by mistake with an ordinary array:
arr=(10 20 30)
echo "[${arr[two]}]"
[10]
Why: two is evaluated as an arithmetic expression. It is an unset variable, which counts as 0, so the result is element 0 rather than an error.
The same rule is what makes a variable index work without $:
idx=1
echo "${arr[idx]} ${arr[$idx]} ${arr[idx+1]}"
20 20 30
Fix: use an associative array when the indexes are words, and keep numeric variables for indexed arrays.
Relying on the Order of Associative Arrays
Why it goes wrong: keys come out of "${!map[@]}" in hash-table order, not in the order they were added and not sorted (lesson 103). A report that looks right with three keys can come out in a different order with four, or after a Bash upgrade.
Fix: sort the keys when order matters:
mapfile -t keys < <(printf '%s\n' "${!map[@]}" | sort)
and loop over "${keys[@]}".
Incrementing from Zero Under set -e
bash -c 'set -e; declare -A c; (( c[a]++ )); echo "not reached"'
echo "status $?"
status 1
Why: the post-increment c[a]++ evaluates to the old value, 0, and an arithmetic command whose value is 0 returns status 1. Under set -e (lesson 119) that status ends the script, on the very first count.
Fix: use pre-increment, which evaluates to the new value, or an assignment:
bash -c 'set -e; declare -A c; (( ++c[a] )); echo "reached: ${c[a]}"'
reached: 1
c[a]=$(( ${c[a]:-0} + 1 )) is another safe form.
Unmatched Globs in Array Assignments
g2=(*.none)
declare -p g2
declare -a g2=([0]="*.none")
Why: when a glob matches no file, Bash leaves the pattern as literal text (lesson 52). The array gets one element that is not a file name, and a loop over it would try to process a file called *.none.
Fix: turn on nullglob while building the array, so an unmatched pattern disappears:
shopt -s nullglob
g3=(*.none)
shopt -u nullglob
declare -p g3
declare -a g3=()
Then check ${#g3[@]} before using the array.
read -a Without -r
read -a parts <<< 'C:\temp\new dir'
declare -p parts
declare -a parts=([0]="C:tempnew" [1]="dir")
Why: without -r, read treats backslashes as escape characters and removes them (lesson 31).
Fix: use read -r -a:
declare -a parts=([0]="C:\\temp\\new" [1]="dir")
declare -p shows each backslash doubled because it prints the value in quoted form; the element itself is C:\temp\new.
Functions That Overwrite Global Arrays
fill() { results=(x y); }
results=(keep)
fill
declare -p results
declare -a results=([0]="x" [1]="y")
Why: variables in a function are global unless declared local (lesson 92). The function replaced the caller's array.
Fix: declare working arrays with local -a (or local -A), and when a function is meant to fill the caller's array, pass the array's name and use a name reference (lesson 104). When using name references, avoid local variables whose names could match the caller's array; the function's own locals shadow it.
Comparing Arrays as Strings
y1=("a b" c)
y2=(a "b c")
[[ "${y1[*]}" == "${y2[*]}" ]] && echo "star says y1 == y2 (wrong)"
star says y1 == y2 (wrong)
Why: both arrays join to the same text, a b c, even though their elements differ.
Fix: compare element by element, checking the counts first, or compare the value part of declare -p, which quotes each element:
[[ "$(declare -p y1 | cut -d= -f2-)" == "$(declare -p y2 | cut -d= -f2-)" ]] ||
echo "declare -p says different"
declare -p says different
cut -d= -f2- keeps everything after the first =, removing the differing variable names so only the contents are compared.
Expecting Arrays in Child Processes
export names
bash -c 'echo "child sees: [$names]"'
child sees: []
Why: the environment passed to other programs can only hold plain strings, so arrays are never exported (lesson 97).
Fix: pass the elements as arguments: bash child.sh "${names[@]}". The child script then receives them in "$@".
Running Array Code with sh
printf 'a=(1 2)\necho ${a[0]}\n' > arr.sh
sh arr.sh
echo "status $?"
arr.sh: 1: Syntax error: "(" unexpected
status 2
Why: on Debian and Ubuntu, sh is Dash, which has no arrays (lesson 97). Associative arrays fail in Dash too, and they also need Bash 4.0, so they are missing from the Bash 3.2 on macOS (lesson 102).
Fix: start array scripts with #!/usr/bin/env bash (lesson 26) and run them as ./script.sh or bash script.sh.
Empty Arrays in Old Bash Versions
Why it goes wrong: before Bash 4.4, expanding "${arr[@]}" of an empty array under set -u stopped the script with an "unbound variable" error. Bash 5.2 expands it to nothing (lesson 100).
Fix: for scripts that must run on older versions, write ${arr[@]+"${arr[@]}"}, which expands to nothing when the array is empty, or check ${#arr[@]} before expanding.
A Quick Diagnostic
When an array behaves strangely, declare -p name usually explains why. It shows:
- the type:
--for a plain string,-afor indexed,-Afor associative; - every index or key that exists, which reveals gaps and overwritten keys;
- every value exactly, in quoted form, which reveals empty elements and joined text.
declare -p list age fr
declare -a list=([0]="ac" [1]="b")
declare -a age=([0]="25")
declare -a fr=([0]="apple" [1]="" [2]="cherry")
In one look, these lines show the += without parentheses, the missing declare -A and the empty element left by pattern removal. ShellCheck (lesson 162) also detects several of these problems automatically, such as unquoted array expansions and assigning an array to a string.