Adding and Removing Array Elements
Bash arrays have no fixed size. Elements can be appended at the end, placed at the front or in the middle, replaced, and removed while a script runs. Bash provides direct syntax for appending (+=) and removing (unset), and the other operations are built from slices and loops. This lesson covers each operation and explains what happens to the indexes, because removing an element leaves a gap that later code has to cope with.
Appending with +=
The += operator with a parenthesized list adds elements after the last one:
tasks=(build test)
tasks+=(deploy)
tasks+=("send report" cleanup)
declare -p tasks
declare -a tasks=([0]="build" [1]="test" [2]="deploy" [3]="send report" [4]="cleanup")
Any number of elements can be added at once, and quoting works as in the original assignment. Appending inside a loop is the standard way to collect results:
results=()
for f in *.log; do
results+=("$f")
done
The Parentheses Matter
Without parentheses, += does something different: it appends text to element 0, because the bare array name refers to element 0 (lesson 97):
t2=(build test)
t2+=deploy
declare -p t2
declare -a t2=([0]="builddeploy" [1]="test")
No error is printed, so this mistake can go unnoticed. The same string-append behavior is useful on purpose when it targets a specific element:
t3=(file)
t3[0]+=".txt"
declare -p t3
declare -a t3=([0]="file.txt")
Where += Puts New Elements
+= places new elements after the highest index in use, not at the position given by the number of elements. In a normal array the two are the same, but in a sparse array they are not. Older scripts often append with arr[${#arr[@]}]=value, which uses the count as the index:
q=(a b c)
q[${#q[@]}]=d
declare -p q
declare -a q=([0]="a" [1]="b" [2]="c" [3]="d")
That works for q, but in a sparse array the count points into a gap, or onto an existing element:
s=([0]=a [5]=b)
s[${#s[@]}]=new
declare -p s
s+=(added)
declare -p s
declare -a s=([0]="a" [2]="new" [5]="b")
declare -a s=([0]="a" [2]="new" [5]="b" [6]="added")
The array had 2 elements, so new went to index 2, in the middle. += placed added after index 5, at the end. Use += for appending and the count-based form only when you are sure the array has no gaps.
Adding to the Front
There is no prepend operator. To put an element first, build a new list from the new value followed by all old elements:
q=(start "${q[@]}")
declare -p q
declare -a q=([0]="start" [1]="a" [2]="b" [3]="c" [4]="d")
The quoted "${q[@]}" expands to the old elements, one word each, before the assignment replaces the array. Every element moves up by one index, and any gaps disappear, because the new array is numbered from 0 again.
Inserting in the Middle
To insert at a position, combine two slices (lesson 98): the elements before the position, the new value, and the elements from the position onward.
q=("${q[@]:0:2}" INSERTED "${q[@]:2}")
declare -p q
declare -a q=([0]="start" [1]="a" [2]="INSERTED" [3]="b" [4]="c" [5]="d")
${q[@]:0:2} gives the first two elements and ${q[@]:2} everything from position 2 to the end. Slices count positions among the existing elements, so this also works on a sparse array, and the result is renumbered from 0.
Replacing an Element
Assigning to an index replaces the value stored there and changes nothing else:
q[0]=BEGIN
declare -p q
declare -a q=([0]="BEGIN" [1]="a" [2]="INSERTED" [3]="b" [4]="c" [5]="d")
Removing an Element with unset
unset (lesson 41) removes a single element when it is given an index:
n=(zero one two three four)
unset 'n[1]'
declare -p n
echo "count ${#n[@]} indices ${!n[@]}"
echo "n[1]=[${n[1]}]"
declare -a n=([0]="zero" [2]="two" [3]="three" [4]="four")
count 4 indices 0 2 3 4
n[1]=[]
The element is gone, but the other elements keep their indexes. The array is now sparse: it has 4 elements, its indexes are 0, 2, 3 and 4, and reading index 1 gives an empty string. Nothing moves down to fill the gap.
Why the Quotes Around n[1]
The quotes in unset 'n[1]' are not decoration. Without them, n[1] is a glob pattern: the brackets form a character class that matches a file named n1. If such a file exists in the current folder, Bash replaces the word with the file name before unset sees it:
m=(a b c)
touch m1
unset m[1]
declare -p m
declare -a m=([0]="a" [1]="b" [2]="c")
The command became unset m1, which removed a variable named m1 (there was none), and the array was left unchanged with no error. In a folder without a matching file, the unquoted form happens to work, which makes the bug depend on where the script runs. Always quote the element name for unset.
Renumbering After Removal
To close the gaps, copy the array onto itself. "${n[@]}" lists only the elements that exist, and the new array is numbered from 0:
n=("${n[@]}")
declare -p n
declare -a n=([0]="zero" [1]="two" [2]="three" [3]="four")
Renumbering is useful before code that walks the array with a counter (lesson 100) or uses the count as an index.
Removing the Last or First Element
A negative index (Bash 4.3 or later) removes the last element, which turns an array into a stack: += pushes and unset 'arr[-1]' pops.
st=(a b c)
top=${st[-1]}
unset 'st[-1]'
echo "$top"; declare -p st
c
declare -a st=([0]="a" [1]="b")
Removing the first element while keeping the array numbered from 0 uses a slice, which turns the array into a queue:
st=(a b c)
first=${st[0]}
st=("${st[@]:1}")
echo "$first"; declare -p st
a
declare -a st=([0]="b" [1]="c")
unset 'st[0]' would also remove the first element, but it would leave the rest at indexes 1 and 2.
An index that does not exist at all is an error for a negative index:
e=(1 2)
unset 'e[-5]'
echo "status $?"
bash: unset: [-5]: bad array subscript
status 1
Removing Elements by Value
unset works by index, so removing every element with a certain value takes a loop. The simplest approach builds a new array of the elements to keep:
fruits=(apple banana cherry banana date)
remove=banana
kept=()
for f in "${fruits[@]}"; do
[[ $f == "$remove" ]] || kept+=("$f")
done
fruits=("${kept[@]}")
declare -p fruits
declare -a fruits=([0]="apple" [1]="cherry" [2]="date")
Both copies of banana were removed and the result is numbered from 0. The quotes around "$remove" make the comparison literal. Without them, the right side of == is a pattern (lesson 70), so a value such as b* would match more than intended.
If the original indexes must be kept, loop over the indexes and unset the matching ones:
fr=(apple banana cherry banana date)
for i in "${!fr[@]}"; do
[[ ${fr[i]} == banana ]] && unset 'fr[i]'
done
declare -p fr
declare -a fr=([0]="apple" [2]="cherry" [4]="date")
"${!fr[@]}" lists the indexes before the loop starts, so removing elements while looping is safe here.
Pattern Replacement Does Not Remove Elements
The ${arr[@]/pattern/replacement} expansion (lesson 54) works on every element, which makes it look like a way to remove values. It is not: an element whose whole value is removed becomes an empty string, and it is still there:
x=(apple banana cherry)
y=("${x[@]/banana}")
declare -p y
z=("${x[@]/an/AN}")
declare -p z
declare -a y=([0]="apple" [1]="" [2]="cherry")
declare -a z=([0]="apple" [1]="bANana" [2]="cherry")
The second example also shows that the pattern matches inside values: it changed the first an in banana. For removal by value, use one of the loops above.
Clearing an Array
There are two ways to empty an array, and they leave different results:
c=(1 2 3)
c=()
declare -p c
unset c
declare -p c
declare -a c=()
bash: declare: c: not found
c=() keeps the variable as an empty array, ready for new elements with +=. unset c removes the variable completely, including its array attribute. Prefer c=() when the array will be filled again, for example at the start of each pass through a loop. Inside a function, local -a c=() gives an empty local array (lesson 92).
A Worked Example: A Task Queue
The operations combine naturally. This script keeps a queue of jobs, adds an urgent job at the front, removes a cancelled one, and then processes the queue from the front until it is empty:
#!/usr/bin/env bash
queue=(backup-db rotate-logs send-report)
queue+=(clean-tmp) # normal job at the end
queue=(fix-disk "${queue[@]}") # urgent job at the front
cancel=send-report # remove a cancelled job
kept=()
for job in "${queue[@]}"; do
[[ $job == "$cancel" ]] || kept+=("$job")
done
queue=("${kept[@]}")
while (( ${#queue[@]} > 0 )); do
job=${queue[0]}
queue=("${queue[@]:1}")
echo "running $job (${#queue[@]} left)"
done
running fix-disk (3 left)
running backup-db (2 left)
running rotate-logs (1 left)
running clean-tmp (0 left)
After the urgent job was added and the cancelled one removed, the queue held four jobs: fix-disk, backup-db, rotate-logs and clean-tmp. Each pass of the while loop takes element 0, rebuilds the array from position 1 onward, and then prints how many jobs remain, so the count reaches 0 with the last job. ${#queue[@]} is the number of elements (lesson 101), and because the array is rebuilt each time, the queue always starts at index 0.