Indexed Arrays in Practice

Indexed Arrays in Practice in Bash: In a fulfilment warehouse, a picker works each customer order with a cart that carries a row of numbered bins -- bin 0, bin…

The Analogy: The Warehouse Order-Picking Cart with Numbered Bins

In a fulfilment warehouse, a picker works each customer order with a cart that carries a row of numbered bins -- bin 0, bin 1, bin 2, and so on down the frame. The order arrives as a pick list, and the picker walks the aisles dropping each item into the next open bin in sequence. The cart is nothing more than an ordered set of numbered slots, and the number painted on the slot is how anyone -- the picker, the packer, the audit clerk -- refers to whatever is inside it.

The numbering is what makes the cart useful. The packer at the end of the line never watched the pick, yet they read bin 0, then bin 1, then bin 2, and rebuild the order in the exact sequence it was gathered. They can ask how many bins are filled to learn the order size, pull the run of bins from 3 to 5 to pack a single carton, or drop a forgotten item into the next free bin without disturbing any of the others. Position is identity: "the thing in bin 4" is a complete and unambiguous instruction.

Crucially, each bin holds one line of the order as a single unit, however bulky that line is. A bin might hold "a boxed set of six glasses" -- one line, one bin -- and the packer treats it as one item because the bin boundary tells them so. The dividers between the bins are not decoration; they are the guarantee that the picker's count and the packer's count agree. Keep the dividers honest and the order flows untouched from pick to pack.

The whole system rests on those dividers, and that is exactly where it breaks. Toss two loose items into one bin without separating them and the packer, reading one bin as one line, counts them as a single item -- and the customer is shorted, silently, while every downstream tally still adds up. Tip the contents of all the bins into one heap to "save space" and the order is still all there, but the boundaries are gone and no one can say where one line ended and the next began. The items were never lost; the structure that made them countable was. An ordered set of slots is only ever as trustworthy as the walls between the slots.


Syntax or Core Structure

An indexed array is an ordered list of values, each reachable by a whole-number position that starts at zero. You build one by listing its elements inside parentheses, read a single element by putting its index in square brackets, and ask for the whole list or the element count with the special subscripts @ and #.

# create an indexed array
files=(report.csv data.json notes.txt)

# index individual elements (numbering starts at zero)
echo "first: ${files[0]}"
echo "third: ${files[2]}"

# how many elements are in the array
echo "count: ${#files[@]}"

# iterate, keeping each element intact
for f in "${files[@]}"; do
  echo "- $f"
done

Output:

first: report.csv
third: notes.txt
count: 3
- report.csv
- data.json
- notes.txt

The array files is the cart; each name sits in a numbered bin. ${files[0]} reads bin zero, ${files[2]} reads bin two, and ${#files[@]} counts the filled bins. The loop walks the bins in order, and the quotes around "${files[@]}" are the dividers: every element reaches the loop body as exactly one word, even a name that once held a space.


Technical Depth: Growing, Slicing, and Quoting the Cart

Appending and reading a run of bins

You rarely know an order's full size in advance, so arrays are built up as you go. The += operator appends one or more elements to the end -- the next free bins. A slice ${arr[@]:start:count} pulls a run of bins, and ${!arr[@]} lists the index numbers themselves, which need not stay contiguous once you begin deleting.

tasks=(build test)
tasks+=(deploy)                  # append one element
tasks+=(docs notify)             # append several at once
echo "all: ${tasks[@]}"
echo "count: ${#tasks[@]}"
echo "slice 1..2: ${tasks[@]:1:2}"
echo "indices: ${!tasks[@]}"

Output:

all: build test deploy docs notify
count: 5
slice 1..2: test deploy
indices: 0 1 2 3 4

Note that ${tasks[@]:1:2} is offset-and-length, not start-and-end: it takes two elements beginning at index 1, giving bins 1 and 2. Reading that second number as an end index is one of the most common off-by-one traps in Bash.

The @ versus * subscript, and why quoting decides everything

The two special subscripts look interchangeable and are not. Quoted, @ gives you each element as its own word; quoted, * joins every element into a single string using the first character of IFS. Unquoted, both throw away the dividers entirely and let the shell re-split and glob every element.

ExpansionWhat you getWhen to reach for it
"${arr[@]}"each element as one separate wordalmost always: loops, passing arguments
"${arr[*]}"all elements joined by the first IFS charbuilding one display string
${arr[@]} unquotedevery element re-split and glob-expandedalmost never
items=("alpha beta" gamma)
echo "quoted @ (boundaries preserved):"
for x in "${items[@]}"; do echo "  [$x]"; done
echo "unquoted (boundaries lost):"
for x in ${items[@]}; do echo "  [$x]"; done

Output:

quoted @ (boundaries preserved):
  [alpha beta]
  [gamma]
unquoted (boundaries lost):
  [alpha]
  [beta]
  [gamma]

The first loop is the honest cart: two bins, two iterations, and the space inside alpha beta stays sealed in its bin. The second loop tips everything into a heap -- three words, three iterations -- and no code downstream can tell that "alpha beta" was ever a single item. The only difference between the two loops is one pair of quotes.

Loading lines from input with mapfile

Reading a file or a command's output into an array by hand is fiddly and easy to get wrong. mapfile -t (also spelled readarray -t) does it in one step, one line per element, with the -t flag trimming the trailing newline from each line.

mapfile -t lines <<'DATA'
first line
second line
third line
DATA
echo "loaded ${#lines[@]} lines"
echo "line 2: ${lines[1]}"

Output:

loaded 3 lines
line 2: second line

Because each line becomes exactly one element, a line containing spaces stays intact -- the divider is drawn at the newline, not at every space. This is the safe replacement for the tempting but broken for line in $(cat file), which word-splits on spaces and shreds any line that is not a single token.

Negative indices and deleting elements

Bash counts from the end with negative indices, so ${arr[-1]} is the last element without your having to compute the length first. Deleting is done with unset, but it leaves a hole: the surrounding elements keep their original index numbers rather than shuffling down to close the gap.

arr=(alpha bravo charlie delta)
echo "last: ${arr[-1]}"
echo "second last: ${arr[-2]}"
unset 'arr[1]'
echo "after unset: ${arr[@]}"
echo "count now: ${#arr[@]}"
echo "indices now: ${!arr[@]}"
arr[1]=BRAVO
echo "restored: ${arr[@]}"

Output:

last: delta
second last: charlie
after unset: alpha charlie delta
count now: 3
indices now: 0 2 3
restored: alpha BRAVO charlie delta

The gap is the important detail. After unset 'arr[1]' the count drops to 3, yet the surviving indices are 0 2 3, so a counted loop from 0 to 2 would read an empty slot at index 1. This is precisely why iterating over "${arr[@]}", which visits only the filled bins, is safer than looping over a computed range whenever an array might be sparse. Negative indices carry their own edge: an index further back than the first element, such as ${arr[-9]} on a four-element array, raises a "bad array subscript" error and expands to nothing, and under set -u it aborts the script as an unbound variable -- so a negative offset derived from arithmetic still needs a bounds check before you trust it.


Real World Example: Assembling a Command's Arguments Safely

The single most valuable use of an indexed array in day-to-day scripting is building up the arguments to another command. Options are often conditional -- add --verbose only in debug mode, add a filter only when one was requested -- and the arguments frequently contain spaces, such as paths. An array is the only construct that lets you assemble those pieces one at a time and then hand them over with every boundary intact.

#!/usr/bin/env bash
# build-args.sh -- assemble a command's arguments in an array, boundaries intact
set -uo pipefail

# a stand-in for the real command: print each argument on its own numbered line
show() {
  local i=1
  for a in "$@"; do
    printf '%d: [%s]
' "$i" "$a"
    (( i++ ))
  done
}

# start with the fixed arguments
args=(--mode fast)

# conditionally add an option based on the first parameter
verbose="${1:-0}"
if [ "$verbose" = "1" ]; then
  args+=(--verbose)
fi

# add a path that contains a space -- it must stay ONE argument
args+=("input files/data.csv")

# expand the array with @ inside quotes: each element becomes exactly one argument
show "${args[@]}"

Run with the verbose flag on, the array carries four arguments and the space in the path survives as a single unit:

bash build-args.sh 1

Output:

1: [--mode]
2: [fast]
3: [--verbose]
4: [input files/data.csv]

Run it with 0 (or with no argument at all, which the default ${1:-0} turns into 0) and the --verbose bin is simply never filled:

bash build-args.sh 0

Output:

1: [--mode]
2: [fast]
3: [input files/data.csv]

The show function stands in for whatever real tool you would call -- rsync, tar, curl -- and it proves the point by printing each argument it actually received on its own line. The path input files/data.csv arrives whole as argument 4 because it lived in one bin and the array was expanded as "${args[@]}".

This script is correct but leans on two guarantees that are easy to lose. The safety property hangs entirely on the single pair of quotes in show "${args[@]}": drop them and the space in the path splits it into two arguments, turning a four-argument call into five with no error and no warning -- the exact "tip it into a heap" failure from the analogy, one character away at all times. Second, the script passes no -- end-of-options marker before its data, so a path that began with a dash would be read by the real command as a flag; a hardened version would build args+=(-- "input files/data.csv"). Finally, ${1:-0} quietly treats any first argument other than 1 as "off", so a caller who typed true expecting verbose output would get none and no diagnostic.


Common Mistakes

  1. Forgetting the [@] and writing ${arr}. A bare ${arr} expands to element zero only, not the whole array. To get every element you must write "${arr[@]}", and to get the count you must write "${#arr[@]}".
  1. Leaving "${arr[@]}" unquoted. Without the quotes, each element is word-split on IFS and glob-expanded, so an element with a space becomes several arguments and an element containing * turns into a list of filenames. Almost every array bug traces back to a missing pair of quotes.
  1. Confusing @ with *. "${arr[*]}" joins everything into one string; "${arr[@]}" keeps the elements separate. Using * where you meant @ collapses your carefully separated arguments into a single blob.
  1. Misreading a slice as start-and-end. ${arr[@]:2:3} means "three elements starting at index 2", not "elements 2 through 3". Treating the second number as an end index silently takes the wrong count.
  1. Assuming indices are always contiguous. After unset 'arr[1]' the array keeps the gap, so ${!arr[@]} might report 0 2 3. Iterating with a counted for ((i=0;...)) loop then reads an empty element at the missing index.
  1. Using for x in $(cat file) to read lines. That word-splits on every space, not just newlines, so any line with a space is torn into pieces. Use mapfile -t arr < file instead.
  1. Quoting the whole array as one string by mistake. Writing cmd "${args[*]}" passes a single argument containing every option glued together, which the target command cannot parse. You almost always want "${args[@]}".
  1. Feeding an array back through eval. Passing "${arr[@]}" through eval re-interprets quoting and defeats the entire point of using an array. If you already have an array, call the command directly with it.
  1. Off-by-one on the last element. The last index is ${#arr[@]} - 1, not ${#arr[@]}. Reading ${arr[${#arr[@]}]} returns nothing because that slot is one past the end.

Best Practices

  • Always expand as "${arr[@]}" with the quotes. This one habit prevents the majority of array bugs; make it automatic and only drop the quotes when you have a specific, considered reason.
  • Use an array, never a string, to hold a command's arguments. Conditionally append options with += and call the command as cmd "${args[@]}" so that spaces and special characters survive the handoff.
  • Prefer mapfile -t for reading lines into an array. It is faster and safer than a hand-written read loop and immeasurably safer than $(cat) word-splitting.
  • Reach for @, not *, unless you specifically want one joined string. Keep * for the rare case where you are deliberately building a single display line.
  • Check ${#arr[@]} before indexing. Under set -u an empty array makes ${arr[0]} an unbound-variable error; guard with a count test or a default value.
  • Copy an array with new=("${old[@]}"). A plain new=$old copies only element zero; the parentheses and [@] copy every element.
  • Do not assume a fixed last index after deletions. Iterate with for x in "${arr[@]}" or over "${!arr[@]}" rather than a counted loop when the array may be sparse.
  • Keep IFS in mind when you use *. "${arr[*]}" joins on the first character of IFS; set IFS locally when you need a specific separator and restore it afterwards.

Practice Exercises

  1. Frequency count. Read a list of words (one per line) into an array with mapfile -t, then print the total number of words and the first and last word, using ${#arr[@]} to locate the last index correctly.
  2. Conditional arguments. Write a script that builds an array of options for a fictional backup command: always include --source ./data, add --compress when an environment variable COMPRESS=1 is set, and add a destination path that contains a space. Print the arguments one per line to prove the boundaries hold.
  3. Safe reverse. Given an array, print its elements in reverse order without losing any element that contains spaces. Iterate over the indices from ${#arr[@]} - 1 down to 0 and expand each element quoted.
  4. Heap versus cart. Take an array with at least one multi-word element and print it twice: once expanded as "${arr[@]}" and once unquoted, counting the iterations each way. Explain in a comment why the two counts differ.