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
- How do you split a string on a delimiter in Bash? [Intermediate]
- What is the difference between glob expansion and regex in the shell? [Intermediate]
- What is the difference between NR and NF in awk? [Advanced]
- How do you use awk to sum or average a column? [Advanced]
- How do you check whether a command exists before using it? [Intermediate]
- What is shellcheck, and what kinds of issues does it catch? [Intermediate]
- What is the difference between sed -i and sed without -i? [Advanced]
- What are exit codes you should use, and what does a non-zero exit signal to a pipeline? [Intermediate]