December 4, 2026

Bash Arrays and Associative Arrays: The Quoting Rules That Decide Everything

A numbered compartment drawer holding one small object per slot, like elements in an indexed array

A filename with a space in it is the standard test of whether a shell script was written carefully. Arrays are Bash’s answer to that test: a way to hold a list of values where each value stays in one piece, spaces and all. They are also one of the easiest parts of the language to get subtly wrong, because four expansions that look nearly identical behave in four different ways. Every example below was run on Bash 5.2.21, and the output is pasted as it appeared.

Video: You Suck at Programming on YouTube

Two kinds of array

Numbered slots and named slots

The Bash reference manual describes two array types. Indexed arrays use whole numbers as subscripts, starting from zero. Associative arrays use arbitrary strings as keys, which makes them the shell’s version of a dictionary or hash map.

The manual sets no ceiling on either: there is no maximum size, and the members of an indexed array do not have to be contiguous. That second point matters more than it sounds, and it comes back in the section on deleting elements.

An indexed array needs no ceremony:

fruits=(apple "blood orange" cherry)
echo "count: ${#fruits[@]}  first: ${fruits[0]}  last: ${fruits[-1]}"
count: 3  first: apple  last: cherry

${#fruits[@]} gives the number of elements. A negative subscript counts back from the end, so -1 is the final element.

Fruits and vegetables arranged on display

Quoted or unquoted, @ or *

Four loops over the same three fruits

The array above holds three elements, one of which contains a space. Looping over it without quotes splits that element in two:

for f in ${fruits[@]}; do echo "  [$f]"; done
  [apple]
  [blood]
  [orange]
  [cherry]

Three elements went in and four came out. The shell expanded the array and then word-split the result, exactly as it would with a plain unquoted variable. Double quotes around the @ form fix it:

for f in "${fruits[@]}"; do echo "  [$f]"; done
  [apple]
  [blood orange]
  [cherry]

Swapping @ for * inside the quotes produces a third behavior:

for f in "${fruits[*]}"; do echo "  [$f]"; done
  [apple blood orange cherry]

One iteration, one long string. The manual spells out the difference: a quoted * expands to a single word with the members joined by the first character of IFS, while a quoted @ expands each element to a separate word.

The rule that follows

"${array[@]}", quotes included, is the form for passing a list to a command or a loop. "${array[*]}" is for joining a list into one string. The unquoted forms have almost no legitimate use.

The joining behavior is handy on purpose. Setting IFS to a comma inside a subshell turns the array into a CSV line without touching the rest of the script:

( IFS=,; echo "${fruits[*]}" )
apple,blood orange,cherry

Appending, deleting and the holes left behind

Adding is simple

+= with parentheses appends:

fruits+=(date)
echo "${#fruits[@]}"
4

Leaving the parentheses off (fruits+=date) does something else entirely: it appends the text to element zero. That slip produces “appledate” and no error message.

Deleting leaves a gap

Removing the second element with unset does not shuffle the others down:

unset 'fruits[1]'
echo "count ${#fruits[@]} indices: ${!fruits[@]}"
echo "fruits[1] is: '${fruits[1]}'"
count 3 indices: 0 2 3
fruits[1] is: ''

The array now has three elements at positions 0, 2 and 3. Position 1 is empty. Any loop that counts from zero to the array length, C-style, will read a blank where “blood orange” used to be and never reach the last element. ${!fruits[@]} lists the indices that exist, which is the reliable way to iterate by position.

Reassigning the array to its own quoted expansion closes the gap:

fruits=("${fruits[@]}")
echo "${!fruits[@]}"
0 1 2

The quotes around 'fruits[1]' in the unset line are not decoration. The manual warns that an unquoted subscripted name is subject to filename expansion, so a file called fruits1 in the current directory could change what the command does.

Slices and the missing subscript

${fruits[@]:1:2} returns two elements starting at offset 1, which printed cherry date on the test machine. And an array referenced with no subscript at all quietly returns only its first element: $fruits printed apple. The manual confirms that ${name} is equivalent to ${name[0]}. A script that works with one-item lists and breaks with longer ones is often suffering from exactly this.

Brown eggs in a carton

Associative arrays

Declare first, always

Named keys require declare -A before the first assignment:

declare -A port
port[ssh]=22; port[https]=443; port[dns]=53
for k in "${!port[@]}"; do echo "  $k -> ${port[$k]}"; done
  dns -> 53
  ssh -> 22
  https -> 443

Two things stand out. ${!port[@]} returns the keys, and the keys came back in an order that matches neither insertion nor the alphabet. Associative arrays are unordered. Output that needs to be stable has to be sorted explicitly:

for k in $(printf '%s\n' "${!port[@]}" | sort); do echo "  $k -> ${port[$k]}"; done
  dns -> 53
  https -> 443
  ssh -> 22

What happens without the declaration

Skipping declare -A does not raise an error. It produces wrong data:

port2[ssh]=22; port2[https]=443
echo "keys ${!port2[@]} vals ${port2[@]}"
keys 0 vals 443

Bash treated port2 as an indexed array, evaluated ssh and https as arithmetic expressions, got zero for both unset names, and wrote both values to slot 0. The second overwrote the first. Nothing in the output hints at the mistake.

Testing whether a key exists

[[ -v port[ssh] ]] is true when the key is set, and the test box confirmed it reports ftp as absent. This is safer than checking for an empty value, since a key can legitimately hold an empty string. The reverse is not allowed. In the manual’s words, “Empty strings cannot be used as associative array keys.”

Filling arrays from files and strings

mapfile for lines

Reading a command’s output into an array, one line per element, is a job for mapfile (also spelled readarray):

mapfile -t lines < <(printf 'one\ntwo words\nthree\n')
echo "count ${#lines[@]} second: [${lines[1]}]"
count 3 second: [two words]

The -t strips the trailing newline from each element. The line containing a space stayed whole, which the popular lines=($(command)) idiom would not manage.

read -a for delimited strings

Splitting one string on a delimiter uses read -ra with a temporary IFS:

IFS=, read -ra parts <<< "a,b c,d"
echo "${#parts[@]} -> [${parts[1]}]"
3 -> [b c]

Because the IFS assignment sits on the same line as read, it applies to that command alone.

Wall of post office boxes

Arrays and functions

Passing the elements

A function receives an array the same way a command does, as separate arguments. The quoting rule from earlier decides whether it arrives intact:

show() { echo "got $# args; second is [$2]"; }
show "${fruits[@]}"
show ${fruits[@]}
got 3 args; second is [blood orange]
got 4 args; second is [blood]

Passing the name

Handing over the elements gives the function a copy. To let a function read or change the caller’s array directly, Bash offers name references, declared with local -n. The function takes the array’s name as a string and treats its local variable as an alias:

total() { local -n arr=$1; local sum=0 x; for x in "${arr[@]}"; do ((sum+=x)); done; echo "sum of $1: $sum"; }
sizes=(10 20 12); total sizes

add_item() { local -n ref=$1; ref+=("$2"); }
add_item fruits "elder berry"; echo "${#fruits[@]} last: ${fruits[-1]}"
sum of sizes: 42
4 last: elder berry

The second function modified an array it never saw by value. The usual caution applies: the alias inside the function should not share a name with the array being passed, or the reference points at itself.

Copies are real copies

Assigning one array to another through the quoted expansion duplicates the data. Changing copy[0] after copy=("${fruits[@]}") left the original untouched on the test box (orig apple copy changed).

Filenames belong in arrays

A glob assigned inside parentheses fills an array with one filename per element, immune to spaces: files=(*.sh) collected two scripts in the test directory. The trap is the empty case. With no match, Bash leaves the pattern as literal text, and none=(*.nomatch) produced an array of one element containing *.nomatch. Turning on shopt -s nullglob first made the same assignment yield a count of zero, which is what a loop over “all matching files” needs when there are none.

A word counter, and a strict-mode surprise

Counting with string keys

The classic use of an associative array is tallying:

declare -A count
for w in the cat the dog the end; do ((count[$w]++)); done
for w in "${!count[@]}"; do echo "$w ${count[$w]}"; done | sort -k2 -nr
the 3
end 1
dog 1
cat 1

The same loop under set -u

Scripts that run with set -u, which treats any unset variable as an error, hit a wall here. On Bash 5.2.21 the identical counting loop stopped with:

arr.sh: line 22: count: unbound variable

The increment reads count[the] before it has ever been assigned, and strict mode objects. Supplying a default makes the read explicit and the script ran cleanly:

count[$w]=$(( ${count[$w]:-0} + 1 ))

Empty arrays caused no trouble under strict mode on this version: looping over "${empty[@]}" with strict mode on simply ran zero times.

Where arrays stop working: not in sh

Arrays are a Bash feature, not a POSIX shell feature. Running the simplest example through sh on the test machine, where sh is dash, failed at the first parenthesis:

sh: 1: Syntax error: "(" unexpected

A script that uses arrays needs #!/bin/bash (or #!/usr/bin/env bash) on its first line, and it needs to be run with bash, not sh script.sh.

Not across process boundaries

An array cannot be exported to a child process as an environment variable. On the test box, a child shell started after export fruits saw an empty array with a count of zero. Passing a list to another script means passing the elements as arguments, other.sh "${fruits[@]}", and letting the receiver collect them from "$@".

Sources

  • GNU Bash Reference Manual, Arrays: https://www.gnu.org/software/bash/manual/html_node/Arrays.html
  • Test commands and output: Bash 5.2.21 on Linux (sh is dash), run for this post

634 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *