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
#!/usr/bin/env bash
declare -A ports=([api]=8080 [web]=80 [db]=5432)
service=
port="${ports[$service]}"
echo "$service:$port"
#!/usr/bin/env bash
declare -A ports=([api]=8080 [web]=80 [db]=5432)
service=
port="${ports[$service]}"
echo "$service:$port"
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.