Arrays and Tables
Indexed Array
Pick an Item
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.
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"
names ← api, web, db
3names=("api" "web" "db")4index=1values this stepapi, web, dbnamesindex ← 1
3names=("api" "web" "db")4index=15selected="${names[$index]}"values this step1indexselected ← web
4index=15selected="${names[$index]}"6echo "$index:$selected"values this stepwebselectedapi, web, dbnames1indexecho "$index:$selected"
5selected="${names[$index]}"6echo "$index:$selected"output1:webvalues this step1indexwebselected
names ← api, web, db
3names=("api" "web" "db")4index=2values this stepapi, web, dbnamesindex ← 2
3names=("api" "web" "db")4index=25selected="${names[$index]}"values this step2indexselected ← db
4index=25selected="${names[$index]}"6echo "$index:$selected"values this stepdbselectedapi, web, dbnames2indexecho "$index:$selected"
5selected="${names[$index]}"6echo "$index:$selected"output2:dbvalues 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.