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.

service
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"
  1. 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=5432ports
  2. service ← api

    3declare -A ports=([api]=8080 [web]=80 [db]=5432)4service="api"5port="${ports[$service]}"
    values this stepapiservice
  3. port ← 8080

    4service="api"5port="${ports[$service]}"6echo "$service:$port"
    values this step8080portapi=8080, web=80, db=5432portsapiservice
  4. echo "$service:$port"

    5port="${ports[$service]}"6echo "$service:$port"
    outputapi:8080
    values this stepapiservice8080port
  1. 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=5432ports
  2. service ← db

    3declare -A ports=([api]=8080 [web]=80 [db]=5432)4service="db"5port="${ports[$service]}"
    values this stepdbservice
  3. port ← 5432

    4service="db"5port="${ports[$service]}"6echo "$service:$port"
    values this step5432portapi=8080, web=80, db=5432portsdbservice
  4. echo "$service:$port"

    5port="${ports[$service]}"6echo "$service:$port"
    outputdb:5432
    values 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.