Common Array Pitfalls

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 105 of 205

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, -a for indexed, -A for 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Common Array Pitfalls and get answers drawn from it.

Signed-in readers only.