Indexed Arrays
An indexed array is like a row of lockers with numbers on the doors. You can use locker 5 without ever using lockers 0 to 4, and the empty ones just stay empty.
In this page:
Syntax
array_name=(value1 value2 value3)
array_name[index]=value
echo "${array_name[index]}"
Indexed Arrays
An indexed array uses numeric indices starting at 0, and indices don't have to be contiguous — you can assign arr[5]=value without ever setting indices 0–4.
${arr[@]} expands to all elements, and ${!arr[@]} expands to all the indices currently in use. This flexibility is unique to Bash's indexed arrays compared to fixed-size arrays in other languages.
Note:
${!arr[@]} lists the indices actually in use, which matters when an array has gaps.Example: Indexed Arrays
#!/bin/bash
colors=("red" "green" "blue")
colors[5]="purple"
for i in "${!colors[@]}"; do
echo "Index $i: ${colors[$i]}"
done
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Starting indexes at 1, when Bash arrays start at 0.
- Writing
$arr[1]instead of${arr[1]}, which prints the first element followed by[1]. - Leaving out the quotes around
"${arr[@]}", which splits items containing spaces.
🔒
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: