Indexed Arrays
In this page:
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
🔒
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: