Bash associative arrays are supported in bash version 4. Here is a quick start tutorial for using bash associative arrays.
Declare and initialize associative array
Before use associative array needs to be declared as shown below:
declare -A hash hash=(["k1"]="v1" ["k2"]="v2")
Get keys and values of associative array
declare -A hash hash=(["k1"]="v1" ["k2"]="v2") echo "keys=${!hash[@]}" echo "vals=${hash[@]}"
keys=k1 k2 vals=v1 v2
Env: GNU bash, version 4.2.46
Iterate over associative array using keys
declare -A hash hash=(["k1"]="v1" ["k2"]="v2") for k in "${!hash[@]}" do echo "${hash[$k]}" done
v1 v2
Env: GNU bash, version 4.2.46
Assign value to a key in associative array
declare -A hash hash=(["k1"]="v1" ["k2"]="v2") hash["k3"]="v3" echo "${!hash[@]}" echo "${hash[@]}"
k1 k3 k2 v1 v3 v2
Env: GNU bash, version 4.2.46