Array Length and Indices
Every Bash array has two separate pieces of information about its shape: how many elements it holds and which index numbers those elements sit at. In a freshly created array the two line up neatly (three elements at indexes 0, 1 and 2), but after elements are removed they drift apart. This lesson shows how to read both, how to tell them apart, and how to use them to answer everyday questions such as "is this array empty?", "what is the last element?" and "where is this value stored?".
Counting Elements with ${#arr[@]}
The number of elements in an array is written ${#arr[@]}. The # in front of a parameter name means "length of", and the [@] subscript applies it to the whole array instead of to one value:
fruits=(apple "dragon fruit" kiwi)
echo "count: ${#fruits[@]}"
echo "count star: ${#fruits[*]}"
count: 3
count star: 3
${#arr[*]} gives the same number. The difference between @ and * matters when the elements themselves are expanded (lesson 98), but not when they are counted, so most scripts simply use ${#arr[@]}.
The count includes only elements that exist. Elements holding an empty string do count, because they exist; indexes that were never assigned, or were removed with unset, do not.
Length of One Element: ${#arr[i]}
Putting an index in the brackets changes the meaning completely. ${#arr[i]} is the length of the string stored at index i, measured in characters:
echo "len of el 1: ${#fruits[1]}"
len of el 1: 12
dragon fruit has 12 characters, including the space. This is the same ${#var} string-length operator from lesson 54, applied to a single element. Numbers are strings too, so the length of an element holding 123 is 3:
n=(5 123 42)
echo "${#n[1]}"
3
The Missing Subscript Trap
Without any subscript, ${#fruits} does not count the array. A bare array name refers to element 0 (lesson 98), so ${#fruits} is the length of apple:
echo "no index: ${#fruits}"
no index: 5
A script that writes ${#arr} when it means the element count usually works by accident in testing (when element 0 happens to be short) and breaks later. The three forms side by side:
| Expression | Meaning | Result for fruits |
|---|---|---|
${#fruits[@]} | number of elements | 3 |
${#fruits[1]} | characters in element 1 | 12 |
${#fruits} | characters in element 0 | 5 |
Listing the Indexes with ${!arr[@]}
An exclamation mark after the opening brace turns the expansion into a list of the indexes in use:
echo "indices: ${!fruits[@]}"
indices: 0 1 2
For a packed array this looks predictable, but the real value of ${!arr[@]} shows up in a sparse array, one with gaps between its indexes:
sp=([0]=a [3]=d [7]=h)
echo "count: ${#sp[@]}"
echo "indices: ${!sp[@]}"
count: 3
indices: 0 3 7
The array has three elements, but its highest index is 7. The count and the indexes answer different questions, and confusing them is the source of most index bugs.
As with values, quote the expansion when looping: for i in "${!sp[@]}". Indexes of an indexed array are always plain integers, so the quotes make no difference here, but the same loop over an associative array (lesson 103) has string keys that can contain spaces.
How Gaps Appear
Gaps come from explicit indexes in an assignment, as above, or from unset (lesson 99):
a=(a b c d e)
unset 'a[1]' 'a[3]'
echo "count ${#a[@]} indices ${!a[@]}"
count 3 indices 0 2 4
Bash does not move the remaining elements down. If a script needs the indexes to be 0 1 2 again, it can rebuild the array from its values, which renumbers it:
a=("${a[@]}")
echo "renumbered: ${!a[@]}"
renumbered: 0 1 2
Finding the Last Element and the Last Index
The Last Value
Since Bash 4.3, a negative index counts from the end of the array, so ${arr[-1]} is the last element whatever its index is:
echo "last value: ${sp[-1]}"
last value: h
The Last Index
The last index is the final item in the index list. Copying that list into its own array makes it easy to read:
idx=("${!sp[@]}")
echo "first index: ${idx[0]}"
echo "last index: ${idx[-1]}"
echo "next free: $(( ${idx[-1]} + 1 ))"
first index: 0
last index: 7
next free: 8
The "next free" index is where arr+=(value) would place a new element, since += appends after the highest index (lesson 99).
Why count - 1 Is Not the Last Index
In other languages the last position is the length minus one. That holds in Bash only for arrays without gaps:
echo "sp[count-1]: [${sp[${#sp[@]}-1]}]"
sp[count-1]: []
The count is 3, so the expression read index 2, which does not exist, and printed an empty string with no error. Use ${arr[-1]} for the last value and the index list for the last index.
Checking Whether an Array Is Empty
An array is empty when its count is zero. Arithmetic evaluation with (( )) (lesson 73) reads naturally:
e=()
echo "empty count: ${#e[@]}"
if (( ${#e[@]} == 0 )); then echo "e is empty"; fi
if [[ ${#fruits[@]} -gt 0 ]]; then echo "fruits has items"; fi
empty count: 0
e is empty
fruits has items
A variable that does not exist at all also reports a count of 0, so the same check covers "never created" and "created empty":
unset u
echo "unset count: ${#u[@]}"
unset count: 0
Reading ${e[-1]} from an empty array is an error, because there is no last element for the negative index to count back from:
bash: e: bad array subscript
Check the count first whenever an array might be empty.
Checking Whether an Index Exists
Testing the value with [[ -n ${arr[i]} ]] cannot tell a missing element from one that holds an empty string. The -v test (Bash 4.3 and later for array elements) checks whether the element is set, independent of its content. Quote the argument so the brackets are not treated as a glob pattern:
if [[ -v 'sp[3]' ]]; then echo "index 3 exists"; fi
if [[ ! -v 'sp[4]' ]]; then echo "index 4 missing"; fi
z=([0]="" [2]=x)
if [[ -v 'z[0]' ]]; then echo "z[0] exists though empty"; fi
index 3 exists
index 4 missing
z[0] exists though empty
The parameter expansion ${arr[i]+set} (lesson 45) gives the same answer and also works in older Bash versions. It expands to the word set when the element exists and to nothing otherwise:
echo "plus form: [${z[0]+set}] [${z[1]+set}]"
plus form: [set] []
Checking That an Index Is in Range
Before reading a position supplied by a user or computed by the script, a range check against the count gives a clear message instead of a silent empty value. For a packed array, the valid range is 0 to count minus 1:
nums=(10 20 30 40 50)
i=5
if (( i >= 0 && i < ${#nums[@]} )); then
echo ok
else
echo "index $i out of range (0-$(( ${#nums[@]} - 1 )))"
fi
index 5 out of range (0-4)
For a sparse array, use the -v test from the previous section instead, because a number inside the range might still be a gap.
Finding the Index of a Value
Bash has no built-in "index of" operation. The usual approach loops over the indexes and compares each element. Wrapped in a function, it prints the first matching index and uses its status to report success:
colors=(red green blue green)
find_index() {
local target=$1; shift
local -a list=("$@")
local i
for i in "${!list[@]}"; do
if [[ ${list[i]} == "$target" ]]; then
echo "$i"
return 0
fi
done
return 1
}
find_index green "${colors[@]}"
find_index purple "${colors[@]}" || echo "purple not found (status $?)"
1
purple not found (status 1)
How it works:
- The first argument is the value to look for;
shiftremoves it so the remaining arguments are the array elements. local -a list=("$@")rebuilds them as a local array. Passing an array this way renumbers it from 0; lesson 104 covers how to pass the array itself when the original indexes matter."$target"is quoted on the right side of==so it is compared as plain text, not as a pattern (lesson 70).return 0after the first match stops the search;return 1after the loop reports that nothing matched, which the caller tests with||orif.
To find every position of a value, drop the early return and print each match:
for i in "${!colors[@]}"; do
[[ ${colors[i]} == green ]] && echo " $i"
done
1
3
Using Lengths in Calculations
Element lengths and counts are ordinary integers, so they fit straight into arithmetic. Finding the longest word compares each element's length with the best one seen so far:
words=(cat elephant ox giraffe)
longest=""
for w in "${words[@]}"; do
(( ${#w} > ${#longest} )) && longest=$w
done
echo "longest: $longest (${#longest})"
longest: elephant (8)
Adding up the lengths of all elements gives the total number of characters stored:
total=0
for f in "${fruits[@]}"; do (( total += ${#f} )); done
echo "chars: $total"
chars: 21
That is 5 for apple, 12 for dragon fruit and 4 for kiwi.
Counts in Slices
The count is also the natural way to describe slices relative to the end of an array (slices were introduced in lesson 98). A negative offset needs a space after the colon, so that Bash does not read :- as the default-value operator:
nums=(10 20 30 40 50)
echo "last two: ${nums[@]: -2}"
echo "all but last: ${nums[@]:0:${#nums[@]}-1}"
last two: 40 50
all but last: 10 20 30 40
The length part of the slice is evaluated as arithmetic, so ${#nums[@]}-1 can be written directly inside it without $(( )).
Choosing the Right Expression
| Question | Expression |
|---|---|
| How many elements are there? | ${#arr[@]} |
How long is the string at index i? | ${#arr[i]} |
| Which indexes are in use? | "${!arr[@]}" |
| What is the last value? | ${arr[-1]} (Bash 4.3+) |
| What is the last index? | last item of "${!arr[@]}" |
| Is the array empty? | (( ${#arr[@]} == 0 )) |
Does index i exist? | [[ -v 'arr[i]' ]] or ${arr[i]+set} |
The next lesson moves from numeric indexes to associative arrays, where the index is an arbitrary string such as a host name or a user name, and the ${!arr[@]} expansion becomes the list of keys.