Creating and Accessing Array Elements
An indexed array (lesson 97) can be filled in several ways: from a list written in the script, one element at a time, from the files that match a pattern, or from the output of a command. Once it exists, its elements are read with the ${name[index]} syntax, either one at a time, all together, or as a slice. This lesson covers each way of creating an array and each way of reading from it, and shows where quoting decides whether the result is correct.
Creating an Array from a List
The most common form is a compound assignment: the name, an equals sign, and a list of values in parentheses.
colors=(red green blue)
declare -p colors
declare -a colors=([0]="red" [1]="green" [2]="blue")
The values are separated by whitespace and numbered from 0 in the order they appear. As with any assignment, there must be no spaces around =.
Inside the parentheses, the normal rules of quoting apply. A value with a space needs quotes, and the list may be spread over several lines, with comments:
colors=(
red # primary
"light green"
blue
)
declare -p colors
declare -a colors=([0]="red" [1]="light green" [2]="blue")
Writing one element per line keeps long lists easy to read and makes changes in version control show up line by line.
Giving Indexes Explicitly
An element can be placed at a chosen index with [index]=value inside the list:
days=([1]=Mon [2]=Tue [7]=Sun)
declare -p days
declare -a days=([1]="Mon" [2]="Tue" [7]="Sun")
Explicit and automatic indexes can be mixed. A value without an index goes to the position after the previous one:
mix=(zero [4]=four five)
declare -p mix
declare -a mix=([0]="zero" [4]="four" [5]="five")
Assigning One Element at a Time
name[index]=value sets a single element. If the array does not exist yet, it is created:
arr[3]=x
declare -p arr
declare -a arr=([3]="x")
This form changes only the element named and leaves the rest of the array untouched, so it is also how you replace an existing value. Assigning a new compound list with name=(...), in contrast, replaces the whole array.
Creating an Array from Files
A glob pattern inside the parentheses expands to the matching file names (lesson 52), and each name becomes one element. Names with spaces are kept whole, because filename expansion happens after word splitting. In a folder containing a b.txt, c.txt and d.log:
txt=(*.txt)
declare -p txt
declare -a txt=([0]="a b.txt" [1]="c.txt")
When nothing matches, Bash leaves the pattern as it was, so the array gets one element containing the literal pattern. The nullglob option (lesson 149) makes a pattern with no match expand to nothing instead:
none=(*.pdf)
declare -p none
shopt -s nullglob
none=(*.pdf)
declare -p none
shopt -u nullglob
declare -a none=([0]="*.pdf")
declare -a none=()
With nullglob, an empty result can be detected by checking that the array has no elements (lesson 101).
Creating an Array from a String or Command Output
Writing an unquoted variable or command substitution inside the parentheses also creates an array, but it goes through word splitting and filename expansion. Both can produce surprises:
list="one two *.log"
words=($list)
declare -p words
declare -a words=([0]="one" [1]="two" [2]="app.log" [3]="d.log")
The *.log in the string was expanded into the names of matching files. The same applies to users=($(command)): it splits the output on spaces, tabs and newlines, so a line such as bo cara becomes two elements:
users=($(printf 'ana\nbo cara\n'))
declare -p users
declare -a users=([0]="ana" [1]="bo" [2]="cara")
Use this form only when you know the values contain no spaces and no glob characters. Bash has two builtins that split input in a controlled way instead.
Splitting a Line with read -a
read -a reads one line and stores its fields in an array. Setting IFS for the command chooses the separator:
IFS=, read -r -a parts <<< "id,name,,city"
declare -p parts
declare -a parts=([0]="id" [1]="name" [2]="" [3]="city")
The empty field between the two commas was kept as an empty element. No filename expansion happens, and the IFS=, setting applies only to this one read command. The -r option keeps backslashes as they are (lesson 31).
One Element per Line with mapfile
mapfile (also called readarray) reads input and stores each line as one element. The -t option removes the newline from the end of each line:
mapfile -t lines < app.log
declare -p lines
declare -a lines=([0]="Error code 7" [1]="ok" [2]="error code 9" [3]="warning")
Spaces inside a line are kept, and nothing is glob-expanded. To read the output of a command this way, use process substitution: mapfile -t lines < <(command) (lesson 151). A pipe such as command | mapfile -t lines does not work, because mapfile would run in a subshell and its array would be lost (lesson 61). mapfile needs Bash 4.0 or later.
Reading a Single Element
An element is read with ${name[index]}. The braces are required:
c=(red green blue yellow)
echo "${c[1]}"
green
Without braces, Bash reads $c (element 0) and then prints [1] as ordinary text:
echo "no braces: $c[1]"
no braces: red[1]
Arithmetic in the Index
The index of an indexed array is an arithmetic expression (lesson 49). A variable inside it can be written with or without $, and calculations are allowed:
i=2
echo "${c[i]} ${c[$i]} ${c[i+1]} ${c[i-2]}"
blue blue yellow red
This is why loops over indexes can write ${arr[i]} directly.
Negative Indexes
A negative index counts from the end of the array: -1 is the last element, -2 the one before it.
echo "last: ${c[-1]} second last: ${c[-2]}"
last: yellow second last: blue
Negative indexes need Bash 4.3 or later. On older versions, the last element is ${c[${#c[@]}-1]}, which only works when the array is not sparse. A negative index that reaches before the start of the array is an error:
echo "${c[-9]}"
echo "after"
bash: c: bad array subscript
after
The script continued after printing the error and an empty line.
Missing Elements
Reading an index that has no element gives an empty string, with no error and status 0:
echo "missing: [${c[10]}]"
missing: []
Under set -u (lesson 120), reading an unset element stops the script, just like reading an unset variable. The default-value forms of lesson 45 work on elements too: ${c[10]:-none} gives none.
Reading All Elements: @ and *
${name[@]} and ${name[*]} both refer to all elements. The difference appears when they are quoted, and it is the same difference as between "$@" and "$*" (lesson 43):
p=("a b" c)
printf '<%s>\n' "${p[@]}"
printf '<%s>\n' "${p[*]}"
printf '<%s>\n' ${p[@]}
<a b>
<c>
<a b c>
<a>
<b>
<c>
"${p[@]}"gives one word per element, exactly as stored. This is the form to use almost every time: in loops, as command arguments, and when copying an array (copy=("${p[@]}"))."${p[*]}"joins all elements into one string, separated by the first character ofIFS(a space by default).- Unquoted
${p[@]}or${p[*]}are split again on whitespace and glob-expanded, soa bbecame two words. Unquoted forms lose the structure the array was created to protect.
Setting IFS changes the join character of "${p[*]}", which gives a quick way to join an array with a separator:
IFS=,; echo "${p[*]}"; unset IFS
a b,c
Remember to restore IFS afterward (here with unset IFS, which returns to the default behavior), or run the join in a subshell: (IFS=,; echo "${p[*]}").
Reading a Slice
${name[@]:start:count} gives count elements beginning at position start. Without count, it gives everything from start to the end. A negative start counts from the end and needs a space after the colon, so that Bash does not read :- as the default-value operator:
echo "slice: ${c[@]:1:2}"
echo "from 2: ${c[@]:2}"
echo "last two: ${c[@]: -2}"
printf '<%s>\n' "${c[@]:1:2}"
slice: green blue
from 2: blue yellow
last two: blue yellow
<green>
<blue>
Quoted, a slice gives one word per element, like "${c[@]}". Slices are the basis for removing the first element and for inserting elements in the middle (lesson 99).
Expansions on Elements
The parameter expansions of lesson 54 work on a single element and on all elements at once:
echo "${#c[3]}"
echo "${c[3]^^} ${c[0]/r/R} ${c[@]^}"
6
YELLOW Red Red Green Blue Yellow
${#c[3]} is the length of the string in element 3 (yellow has 6 characters), not the number of elements. ${c[3]^^} uppercases one element, ${c[0]/r/R} replaces text in one element, and ${c[@]^} capitalizes the first letter of every element. Applied with [@], each expansion works element by element, and the result can be stored as a new array: caps=("${c[@]^}"). The number of elements in an array is ${#c[@]}, covered with indexes in lesson 101.