Indexed Arrays in Depth
In this page:
Declaring and Assigning Indexed Arrays
Indexed arrays can be declared explicitly with declare -a arrname or simply created by assigning a parenthesized list of values, arr=(a b c). Either way, Bash automatically numbers the elements starting at index 0.
Example: Declaring and Assigning Indexed Arrays
#!/bin/bash
declare -a numbers
numbers=(10 20 30)
echo "First: ${numbers[0]}, Second: ${numbers[1]}, Third: ${numbers[2]}"
Login to try C/C++/Java/PHP code in the editor
Assigning to Specific Indices
Individual elements can be set directly by index, arr[5]=value, without needing to have previously assigned the indices before it. This can produce a sparse array, where some numeric indices between the lowest and highest simply don't exist.
Warning: The array has only 2 real elements even though the highest index is 5, because indices 1-4 were never assigned.
Example: Assigning to Specific Indices
#!/bin/bash
declare -a grid
grid[0]="start"
grid[5]="end"
echo "grid[0] = ${grid[0]}"
echo "grid[5] = ${grid[5]}"
echo "Number of actual elements: ${#grid[@]}"
Login to try C/C++/Java/PHP code in the editor
Modifying an Existing Element
An existing array element can be overwritten just like a normal variable, by assigning a new value to its specific index. This does not affect any other elements in the array.
Example: Modifying an Existing Element
#!/bin/bash
colors=(red green blue)
colors[1]="yellow"
echo "Updated array: ${colors[@]}"
Login to try C/C++/Java/PHP code in the editor
Printing All Elements and Their Count
${arr[@]} expands to all elements as separate words, and ${#arr[@]} gives the total count of elements currently present. These two expansions are the backbone of nearly every array-processing pattern in Bash.
Example: Printing All Elements and Their Count
#!/bin/bash
planets=(Mercury Venus Earth Mars)
echo "All planets: ${planets[@]}"
echo "Total count: ${#planets[@]}"
Login to try C/C++/Java/PHP code in the editor
- Assuming array indices must be assigned consecutively starting at 0; you can assign directly to any index, e.g.
arr[10]=x, which creates a sparse array with gaps in between. - Forgetting
${arr[@]}vs${arr[*]}differ when quoted, the same subtlety as$@vs$*for positional parameters. - Trying to get an array's length with
${#arr}instead of${#arr[@]}; the former only gives the character length of the first element.
- Declare explicitly with
declare -a arror just assign directly,arr=(a b c). - Individual elements can be assigned or read by explicit index:
arr[2]=value,${arr[2]}. - Arrays can be sparse -- assigning to
arr[100]doesn't create 100 empty slots before it. ${arr[@]:offset:length}and other expansions covered later in this chapter all build on the indexed array fundamentals here.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: