Indexed arrays and sparse indices
An indexed array stores several strings under integer indices. Unlike a scalar, it can keep a list without joining the values into one string. Start with items=(red blue) or declare the type explicitly with declare -a items. Indices begin at zero; access an element using "${items[0]}". Use items[4]=green to assign a specific index. Missing indices do not occupy elements. ${#items[@]} counts assigned elements, including assigned empty strings; "${!items[@]}" lists assigned indices. Bash permits negative references relative to one beyond the maximum index: -1 refers to the highest assigned index of a nonempty indexed array. Indexed subscripts are arithmetic expressions, so do not feed arbitrary external text into them; validate bounded decimal input as taught in Chapter 8. Arrays are Bash-specific, not POSIX sh syntax. A missing element expands to an empty string in the default shell settings, just like an assigned empty element. To distinguish them, use "${items[2]+present}" with a fixed index.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Create and access
declare -a items=(red 'dark blue')printf '%s\n' "${items[0]}" "${items[1]}"Expected stdout:
reddark blueThe second element contains a space but remains one string.
Inspect sparse indices
items=([0]=alpha [5]=omega)printf 'count=%s\n' "${#items[@]}"for i in "${!items[@]}"; do printf '%s=%s\n' "$i" "${items[i]}"doneExpected stdout:
count=20=alpha5=omegaOnly two indices are assigned; i is a trusted index from the array.
Empty element and last index
items=([2]='' [7]=last)printf 'count=%s\nlast=%s\nempty=[%s]\n' "${#items[@]}" "${items[-1]}" "${items[2]}"Expected stdout:
count=2last=lastempty=[]The empty string is assigned and counts as an element.
Common mistakes
An array with indices 0 and 5 has two elements, not six. Avoid looping from zero to length minus one when gaps are possible. Enumerate actual indices instead.
Practice
Create an array with indices 0, 3 and 8, including an empty value. Print the count and each existing index with its value. Predict what index -1 returns.
Next: Array expansion with @ and *