Arrays and Tables
Associative Array
Look Up a Value
Associative arrays use string keys instead of numeric indexes. They are useful for small lookup tables inside scripts.
Program
Play the script to choose the service key and see the configured port.
associative_array_lookup.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
declare -A ports=([api]=8080 [web]=80 [db]=5432)
service="api"
port="${ports[$service]}"
echo "$service:$port"
#!/usr/bin/env bash
declare -A ports=([api]=8080 [web]=80 [db]=5432)
service="db"
port="${ports[$service]}"
echo "$service:$port"
ports ← api=8080, web=80, db=5432
3declare -A ports=([api]=8080 [web]=80 [db]=5432)4service="api"values this stepapi=8080, web=80, db=5432portsservice ← api
3declare -A ports=([api]=8080 [web]=80 [db]=5432)4service="api"5port="${ports[$service]}"values this stepapiserviceport ← 8080
4service="api"5port="${ports[$service]}"6echo "$service:$port"values this step8080portapi=8080, web=80, db=5432portsapiserviceecho "$service:$port"
5port="${ports[$service]}"6echo "$service:$port"outputapi:8080values this stepapiservice8080port
ports ← api=8080, web=80, db=5432
3declare -A ports=([api]=8080 [web]=80 [db]=5432)4service="db"values this stepapi=8080, web=80, db=5432portsservice ← db
3declare -A ports=([api]=8080 [web]=80 [db]=5432)4service="db"5port="${ports[$service]}"values this stepdbserviceport ← 5432
4service="db"5port="${ports[$service]}"6echo "$service:$port"values this step5432portapi=8080, web=80, db=5432portsdbserviceecho "$service:$port"
5port="${ports[$service]}"6echo "$service:$port"outputdb:5432values this stepdbservice5432port
associative array
`declare -A` creates a map from string keys to values.
lookup key
The key inside brackets selects the matching stored value.
small table
A shell map is a compact way to keep small configuration tables near the script.