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]}"
donePreparing 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
- What is the purpose of the shebang line, and what does #!/bin/bash do? [Basic]
- What is the difference between sh and bash? [Basic]
- How do you make a script executable and run it? [Basic]
- What is the difference between running a script with./script.sh, bash script.sh, and source script.sh? [Basic]
- What does sourcing a script do differently from executing it? [Basic]
- How do you declare a variable in Bash, and why are spaces around = not allowed? [Basic]
- What is the difference between $var and ${var}? [Basic]
- What is the difference between single quotes and double quotes in Bash? [Basic]