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.
More on Arrays, conditionals and loops
How do you declare, populate and iterate an indexed array?BeginnerWhat is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do you read a command's output into an array correctly?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerWhy does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?IntermediateList the most-used file test operators.Beginner