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.
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 hashmapAssign 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
key1Get 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]}
donekey2 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
value1Get length of associative array
To get the length of an associative array we need to access hashmap variable in the following form
echo ${#hashmap[@]}
2I hope you found this short article useful :)