Indexed Arrays in Bash
An indexed array is a variable that holds a list of values, each stored under a number called its index. Where an ordinary variable holds one string, an array holds many, and each one can be read, changed or removed on its own. Arrays are the tool Bash offers for any list whose items may contain spaces or special characters: file names, command-line options, lines of a file, or results collected in a loop.
Bash has two kinds of arrays. Indexed arrays, covered in this lesson and lessons 98 to 101, use whole numbers as indexes. Associative arrays (lessons 102 and 103) use strings as keys.
Why Arrays Exist
Before arrays, the usual way to keep a list in a shell script was a single string with the items separated by spaces. That breaks as soon as an item contains a space:
files="report one.txt notes.txt"
for f in $files; do echo "[$f]"; done
[report]
[one.txt]
[notes.txt]
The string has no memory of where one item ends and the next begins. The unquoted $files is split on every space (word splitting, lesson 53), so the file name report one.txt became two words. Quoting "$files" does not help either, because then the whole string is one item.
An array stores each item separately, so nothing has to be guessed:
files=("report one.txt" "notes.txt")
for f in "${files[@]}"; do echo "[$f]"; done
[report one.txt]
[notes.txt]
The quotes in the assignment decide where each item begins and ends, and the quoted expansion "${files[@]}" gives back exactly those items, one word per item, with spaces inside them kept.
How an Indexed Array Is Organized
Conceptually, an indexed array is a table of index and value pairs:
fruits=(apple banana cherry)
declare -p fruits
declare -a fruits=([0]="apple" [1]="banana" [2]="cherry")
declare -p (lesson 92) prints a variable together with its attributes. The -a flag marks an indexed array, and each element appears with its index in square brackets. A few properties follow from this:
- Indexes start at 0. The first element is
[0], the second[1], and so on. - Every value is a string. Bash has no separate number, boolean or nested-list types. A value such as
42is stored as text and only treated as a number inside arithmetic (lesson 49). - Indexes do not have to be consecutive. An array may have elements at 0, 5 and 9 and nothing in between. Such an array is called sparse.
- The size is not fixed. Elements can be added and removed at any time (lesson 99).
The Basic Operations
The syntax for working with arrays always uses braces. These are the operations you will use most, each covered in detail in the following lessons:
fruits=(apple banana cherry)
echo "first: ${fruits[0]}"
echo "third: ${fruits[2]}"
echo "all: ${fruits[@]}"
echo "count: ${#fruits[@]}"
echo "indices: ${!fruits[@]}"
first: apple
third: cherry
all: apple banana cherry
count: 3
indices: 0 1 2
| Expression | Meaning | Lesson |
|---|---|---|
arr=(a b c) | create an array from a list | 98 |
${arr[i]} | the element at index i | 98 |
"${arr[@]}" | all elements, each as a separate word | 98, 100 |
${#arr[@]} | the number of elements | 101 |
${!arr[@]} | the list of indexes that are in use | 100, 101 |
arr+=(d) | append one or more elements | 99 |
unset 'arr[i]' | remove one element | 99 |
The Array Name Alone Means Element 0
Using an array name without an index does not give the whole array. It gives element 0:
echo "plain \$fruits: $fruits"
plain $fruits: apple
This is a common surprise for beginners who expect $fruits to print the list. The reverse is also true: Bash treats every ordinary variable as if it were element 0 of an array, and assigning to another index turns it into an array:
name=Ana
echo "${name[0]} [${name[1]}]"
declare -p name
name[1]=Bo
declare -p name
Ana []
declare -- name="Ana"
declare -a name=([0]="Ana" [1]="Bo")
declare -- means a plain variable with no attributes. After name[1]=Bo, the same variable became an indexed array with the old value at index 0.
Sparse Arrays
Indexes can be given explicitly when the array is created. Elements that were never set simply do not exist:
nums=([0]=10 [5]=50 [9]=90)
declare -p nums
echo "count: ${#nums[@]} indices: ${!nums[@]}"
echo "nums[3]=[${nums[3]}]"
declare -a nums=([0]="10" [5]="50" [9]="90")
count: 3 indices: 0 5 9
nums[3]=[]
The array has three elements, not ten. Reading a missing index such as nums[3] gives an empty string without an error, just like reading an unset variable. Sparse arrays appear more often than you might expect, because removing an element with unset leaves a gap (lesson 99). This is why loops that walk an array by counting from 0 to the length can miss elements, and why looping over "${!arr[@]}" is safer (lesson 100).
Declaring an Array Explicitly
An array is created automatically by the first assignment, so a declaration is optional. declare -a makes the intent clear and creates an empty array:
declare -a empty
declare -p empty
echo "count ${#empty[@]}"
declare -a empty
count 0
Inside a function, local -a name creates a local array (lesson 92). Attributes can be combined with -a: for example declare -ai makes an array whose elements are evaluated as integers when they are assigned:
declare -ai scores=(10 20)
scores[2]="5 + 5"
declare -p scores
declare -ai scores=([0]="10" [1]="20" [2]="10")
Values of Any Kind
Because every element is a string, one array can hold numbers, words, empty strings and text with spaces side by side:
mixed=(42 "two words" 3.14 "")
echo "count ${#mixed[@]}"
printf '<%s>\n' "${mixed[@]}"
count 4
<42>
<two words>
<3.14>
<>
The empty string is a real element and is counted. printf repeats its format once for each argument, which makes it a convenient way to see exactly what an array contains.
A Practical Use: Building Command Arguments
One of the most valuable uses of arrays is collecting the arguments of a command. Storing options and a pattern in a plain string breaks on spaces, but an array keeps each argument whole. Given an app.log that contains Error code 7, ok, error code 9 and warning:
grep_opts=(-i -n)
pattern="error code"
grep "${grep_opts[@]}" "$pattern" app.log
1:Error code 7
3:error code 9
"${grep_opts[@]}" expanded to the two words -i and -n, and the pattern with its space stayed a single argument. A script can add options to such an array step by step, for example grep_opts+=(-w) when the user passes a flag, and run the command once at the end.
Limits of Bash Arrays
Arrays in Bash are simpler than lists in general-purpose languages, and a few limits are worth knowing from the start:
- No nesting. An element cannot itself be an array. Lists of lists are usually handled with a separator inside each element, parallel arrays with the same indexes, or associative arrays with compound keys.
- No export. Arrays cannot be passed to child processes through the environment:
fruits=(apple banana cherry)
export fruits
bash -c 'echo "child sees: [${fruits[0]}]"'
child sees: []
- Passing to functions needs care. A function receives its arguments as a flat list, so arrays are passed by expanding them or by name (lesson 104).
- Bash only. Arrays are not part of the POSIX shell standard. Dash, the
shof Debian and Ubuntu, rejects the syntax:
$ dash -c 'a=(1 2 3); echo ${a[0]}'
dash: 1: Syntax error: "(" unexpected
Scripts that use arrays need a Bash shebang (#!/usr/bin/env bash, lesson 26) and must be run with Bash, not sh script.sh.
Indexed arrays exist in every Bash version still in use, including Bash 3.2 on macOS, but some array features covered in the next lessons are newer. mapfile and associative arrays need Bash 4.0, and negative indexes such as ${arr[-1]} need Bash 4.3.