Bash associative array tutorial

Bash associative arrays are supported in bash version 4. Here is a quick start tutorial for using bash associative arrays.

bash-associative-array

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.3.11

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.3.11

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.3.11
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments