Indexed arrays keep an ordered list of values. A numeric index selects one value without rewriting the rest of the script.

Program

Play the script to choose the index and see which array element is selected.

index
indexed_array_pick.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash

names=("api" "web" "db")
index=1
selected="${names[$index]}"
echo "$index:$selected"
#!/usr/bin/env bash

names=("api" "web" "db")
index=2
selected="${names[$index]}"
echo "$index:$selected"
  1. names ← api, web, db

    3names=("api" "web" "db")4index=1
    values this stepapi, web, dbnames
  2. index ← 1

    3names=("api" "web" "db")4index=15selected="${names[$index]}"
    values this step1index
  3. selected ← web

    4index=15selected="${names[$index]}"6echo "$index:$selected"
    values this stepwebselectedapi, web, dbnames1index
  4. echo "$index:$selected"

    5selected="${names[$index]}"6echo "$index:$selected"
    output1:web
    values this step1indexwebselected
  1. names ← api, web, db

    3names=("api" "web" "db")4index=2
    values this stepapi, web, dbnames
  2. index ← 2

    3names=("api" "web" "db")4index=25selected="${names[$index]}"
    values this step2index
  3. selected ← db

    4index=25selected="${names[$index]}"6echo "$index:$selected"
    values this stepdbselectedapi, web, dbnames2index
  4. echo "$index:$selected"

    5selected="${names[$index]}"6echo "$index:$selected"
    output2:db
    values this step2indexdbselected
indexed array An indexed array stores values by numeric position.
array element `${names[$index]}` reads one element from the array.
zero-based index The first array position is index `0`; index `1` is the second value.