Looping Through Arrays
Most work with arrays happens inside a loop: checking every server in a list, processing every file, adding up every number. Bash offers two main ways to walk an array. A loop over the values gives each element in turn. A loop over the indexes gives each position, from which the value can be read and also changed. This lesson covers both, explains which to choose, and shows the patterns that build on them: changing elements, filtering into a new array, walking two arrays side by side, and stopping early.
Looping Over Values
The standard form passes the quoted expansion "${arr[@]}" to a for loop (lesson 78):
servers=("web 01" db cache)
for s in "${servers[@]}"; do
echo "checking [$s]"
done
checking [web 01]
checking [db]
checking [cache]
"${arr[@]}" expands to one word per element, so the loop runs once per element and s holds each value exactly as stored, spaces included. This form also handles sparse arrays correctly, because it lists only the elements that exist.
Why the Quotes Are Required
The two other spellings look similar and give wrong results:
for s in ${servers[@]}; do echo "[$s]"; done
[web]
[01]
[db]
[cache]
for s in "${servers[*]}"; do echo "[$s]"; done
[web 01 db cache]
Unquoted ${servers[@]} is split again on whitespace (and glob-expanded), so web 01 became two passes. Quoted "${servers[*]}" joins everything into a single string, so the loop ran only once. Only "${arr[@]}" gives one pass per element.
Looping Over Indexes
"${!arr[@]}" expands to the list of indexes that are in use. Looping over it gives access to both the position and the value:
for i in "${!servers[@]}"; do
echo "$i: ${servers[i]}"
done
0: web 01
1: db
2: cache
Inside the brackets, the index is arithmetic, so ${servers[i]} works without a $ before i (lesson 98). The index loop is the right choice when you need the position, for example to number the output from 1:
for i in "${!servers[@]}"; do
printf '%d) %s\n' "$((i + 1))" "${servers[i]}"
done
1) web 01
2) db
3) cache
C-Style Loops and Sparse Arrays
A counting loop (lesson 79) from 0 to the number of elements is common in scripts written by programmers coming from other languages:
for (( i = 0; i < ${#arr[@]}; i++ )); do
echo "${arr[i]}"
done
It works only when the indexes are exactly 0, 1, 2, ... with no gaps. On a sparse array, such as one where elements were removed with unset (lesson 99), it reads the wrong positions:
sp=([0]=a [3]=d [7]=h)
for (( i = 0; i < ${#sp[@]}; i++ )); do echo "i=$i [${sp[i]}]"; done
i=0 [a]
i=1 []
i=2 []
The array has 3 elements, so the loop visited indexes 0, 1 and 2, found nothing at 1 and 2, and never reached d and h. Looping over "${!sp[@]}" visits exactly the indexes in use:
for i in "${!sp[@]}"; do echo "i=$i [${sp[i]}]"; done
i=0 [a]
i=3 [d]
i=7 [h]
Use the C-style loop only when you need something the index list cannot give, such as walking backward or stepping by two, and only on arrays you know have no gaps (renumber with arr=("${arr[@]}") first if in doubt).
Walking Backward
Counting down from the last index is one of those cases:
vals=(4 17 9 23 2)
for (( i = ${#vals[@]} - 1; i >= 0; i-- )); do
printf '%s ' "${vals[i]}"
done
echo
2 23 9 17 4
Changing Elements Inside a Loop
The loop variable of a value loop holds a copy of each element. Changing it does not change the array:
nums=(1 2 3)
for n in "${nums[@]}"; do n=$(( n * 10 )); done
declare -p nums
declare -a nums=([0]="1" [1]="2" [2]="3")
To change the array itself, loop over the indexes and assign to arr[i]:
for i in "${!nums[@]}"; do
nums[i]=$(( nums[i] * 10 ))
done
declare -p nums
declare -a nums=([0]="10" [1]="20" [2]="30")
Inside $(( )), array elements can also be written without $ and braces, as nums[i].
Adding Elements During a Loop
The list that a for loop walks is expanded once, before the first pass. Elements added to the array inside the loop are not visited by the same loop:
w=(1 2 3)
for x in "${w[@]}"; do
w+=("$x$x")
echo "saw $x"
done
declare -p w
saw 1
saw 2
saw 3
declare -a w=([0]="1" [1]="2" [2]="3" [3]="11" [4]="22" [5]="33")
The loop ran three times even though the array grew to six elements. This makes it safe to append while looping, and it also means that a work list which must process items added on the way needs a while loop that checks the array each time, like the queue in lesson 99.
Building a New Array from a Loop
Filtering is a loop that appends matching elements to a new array:
files=(report.txt photo.jpg notes.txt song.mp3)
txt=()
for f in "${files[@]}"; do
[[ $f == *.txt ]] && txt+=("$f")
done
declare -p txt
declare -a txt=([0]="report.txt" [1]="notes.txt")
Starting with txt=() makes sure the result is empty even if a variable with that name existed before. The pattern *.txt on the right of == is unquoted on purpose, so it is matched as a pattern (lesson 70).
Calculating Over All Elements
Totals, maximums and counts follow the same shape: initialize, update in the loop, use the result afterward:
vals=(4 17 9 23 2)
sum=0 max=${vals[0]}
for v in "${vals[@]}"; do
(( sum += v ))
(( v > max )) && max=$v
done
echo "sum=$sum max=$max"
sum=55 max=23
The maximum starts from the first element rather than from 0, so the code also works when every value is negative.
Walking Two Arrays Together
Bash has no list of pairs, so related values are often kept in parallel arrays that share the same indexes. One index loop reads both:
names=(Ana Bo Cara)
scores=(91 78 85)
for i in "${!names[@]}"; do
printf '%-5s %3d\n' "${names[i]}" "${scores[i]}"
done
Ana 91
Bo 78
Cara 85
%-5s prints the name left-aligned in 5 columns and %3d prints the score right-aligned in 3 (lesson 30). Parallel arrays must be kept in step: removing an element from one without removing the same index from the other breaks every pair after it. When the pairs are really names with values, an associative array (lesson 102) is often clearer.
Stopping Early and Skipping Elements
break and continue (lesson 84) work in array loops like in any other loop:
files=(report.txt photo.jpg notes.txt song.mp3)
for f in "${files[@]}"; do
[[ $f == *.jpg ]] && continue
[[ $f == *.mp3 ]] && break
echo "processing $f"
done
processing report.txt
processing notes.txt
photo.jpg was skipped, and the loop ended at song.mp3. A while loop with an index is useful when the loop should stop at the first match and the position of that match is needed afterward:
vals=(4 17 9 23 2)
i=0
while (( i < ${#vals[@]} )); do
(( vals[i] > 10 )) && { echo "first over 10: ${vals[i]} at $i"; break; }
(( i++ )) || true
done
first over 10: 17 at 1
The || true after (( i++ )) matters only in scripts with set -e: when i is 0, (( i++ )) returns status 1 (lesson 73), which would end such a script.
Looping Over Part of an Array
A slice (lesson 98) restricts the loop to some of the elements:
for s in "${files[@]:1:2}"; do echo "[$s]"; done
[photo.jpg]
[notes.txt]
This skips a header element, processes items in batches, or leaves out the first value when it has already been handled.
Empty Arrays
A loop over an empty array simply does not run, and its status is 0:
emp=()
for x in "${emp[@]}"; do echo "never"; done
echo "empty loop status $?"
empty loop status 0
In Bash 5.2, this also works in a script with set -u (lesson 120):
set -u
e=()
for x in "${e[@]}"; do :; done
echo "ok under set -u"
ok under set -u
Bash versions before 4.4 treated "${e[@]}" of an empty array as an unset variable under set -u and stopped the script. Scripts that must run on such versions, including Bash 3.2 on macOS, often write ${e[@]+"${e[@]}"}, which expands to nothing when the array is empty.
Lines of a File
Combined with mapfile (lesson 98), an array loop processes a file line by line, with each line kept whole:
printf 'alpha\nbeta gamma\n' > lines.txt
mapfile -t L < lines.txt
for l in "${L[@]}"; do echo "line: [$l]"; done
line: [alpha]
line: [beta gamma]
Reading everything into an array first is convenient when the lines are needed more than once or in a different order. For very large files, a while read loop (lesson 80, and lesson 114) handles one line at a time without keeping the whole file in memory.
Lists of Lists
An element cannot itself be an array (lesson 97). When each item of a list has its own members, a common approach keeps the members in one string per element and splits it inside the loop with read -a:
groups=("a b" "c d e")
for g in "${groups[@]}"; do
read -r -a members <<< "$g"
echo "group of ${#members[@]}: ${members[*]}"
done
group of 2: a b
group of 3: c d e
This works when the members never contain the separator, here a space. With a different IFS for read, the members can be separated by commas or colons instead.
Printing an Array Without a Loop
Sometimes a loop is not needed at all. printf repeats its format for every argument, so it prints one element per line, and a subshell with a changed IFS joins the elements with a separator (lesson 98):
printf '%s\n' "${files[@]}" | sort
(IFS=,; echo "${files[*]}")
notes.txt
photo.jpg
report.txt
song.mp3
report.txt,photo.jpg,notes.txt,song.mp3
Piping printf '%s\n' "${arr[@]}" into sort, grep or uniq lets the standard text tools work on an array. The result can be read back into an array with mapfile -t sorted < <(printf '%s\n' "${files[@]}" | sort).