Bash: associative arrays how to

An associative array stores multiple data with keys corresponding values, each value can be accessed with the key of the array.

Bash: associative arrays how to
Photo by Gabriel Heinzer on Unsplash

An associative array stores multiple data with keys corresponding values, each value can be accessed with the key of the array.

How to create an associative array

First we need to declare the array using the declare command, -A parameter instructs declare to create an associative array; hashmap is the name of our array variable.

declare -A hashmap

Assign a key and a corresponding value

Creating a key and assign a corresponding value is pretty easy

hashmap["key1"]="value1" 
hashmap["key2"]="value2"

Accessing value of key

Accessing the value of a key is quite easy as well

echo ${hashmap[$key]}

Accessing all array keys

To access the keys we need to iterate the hashmap variable in this form

${!hashmap[@]}

Then just get each key variable

for key in ${!hashmap[@]}; 
do  
   echo $key; 
done 
 
key2 
key1

Get key / values

To get key and value in the same loop you can use for again.

for key in ${!hashmap[@]}; 
do 
   echo $key" has value "${hashmap[$key]} 
done

key2 has value value2
key1 has value value1

Get only values

To get the values of an associative array and ignore the keys we need to iterate hashmap in the following form

${hashmap[@]}

then just perform the for command

for value in ${hashmap[@]}; 
do 
   echo $value; 
done 
 
value2 
value1

Get length of associative array

To get the length of an associative array we need to access hashmap variable in the following form

echo ${#hashmap[@]} 
 
2

I hope you found this short article useful :)

Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…