Interview Scripting (Bash, Groovy)

What is an associative array, and how do you use one? [Intermediate]

Answer

An associative array is a Bash map from string keys to values. It is declared with declare -A and is useful for lookups such as service-to-port, environment-to-cluster, or counters by key.

Technical explanation

Associative arrays require Bash 4 or newer, so they are not available in old macOS system Bash 3.x unless a newer Bash is installed.

Use ${map[$key]} to read values and ${!map[@]} to iterate keys.

Under set -u, use ${map[$key]:-default} when a key might be absent.

Hands-on example

declare -A port_by_service=(

[api]=8080

[worker]=9090

)

svc="api"

echo "${svc} port is ${port_by_service[$svc]}"

for key in "${!port_by_service[@]}"; do

echo "$key -> ${port_by_service[$key]}"

done

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Scripting (Bash, Groovy) interview questions

← All Scripting (Bash, Groovy) questions