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

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:

  1. Indexed Arrays
Syntax
bash
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

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

for i in "${!colors[@]}"; do
    echo "Index $i: ${colors[$i]}"
done
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
  1. Starting indexes at 1, when Bash arrays start at 0.
  2. Writing $arr[1] instead of ${arr[1]}, which prints the first element followed by [1].
  3. Leaving out the quotes around "${arr[@]}", which splits items containing spaces.

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.