Interview Prep/Shell Scripting/Arrays, conditionals and loops

How do associative arrays work and what are they good for in DevOps scripts?

IntermediateConceptArrays, conditionals and loops
Answer

Associative arrays (Bash 4+) map string keys to values; declare them with declare -A first.

declare -A replicas=([api]=3 [worker]=2 [web]=4)
replicas[cron]=1
for svc in "${!replicas[@]}"; do
  kubectl scale deploy "$svc" --replicas="${replicas[$svc]}"
done
[[ -v replicas[api] ]] && echo "api configured"

# Counting: requests per status code
declare -A count
while read -r code; do (( count[$code]++ )) || true; done < <(awk '{print $9}' access.log)

Key order is not guaranteed; pipe through sort if order matters. macOS ships Bash 3.2, which fails with declare: -A: invalid option.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arrays, conditionals and loops