← Back to Bash Course | Chapter 6: Arrays | Lesson 3 of 10

Indexed Arrays

In this page:

  1. Indexed Arrays

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

bash
#!/bin/bash
colors=("red" "green" "blue")
colors[5]="purple"

for i in "${!colors[@]}"; do
    echo "Index $i: ${colors[$i]}"
done

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.