dictionaries in bash

Dictionary / associative arrays / hash map are very useful data structures and they can be created in bash. They work quite similar as in python (and other languages, of course with fewer features :)). We will go over a few examples.

dictionaries were added in bash version 4.0 and above.

To check the version of bash run following:

bitarray$bash --version
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Note: you have to declare associative array otherwise bash will take it as index variable:

Declare an associative array / dictionary / hash map

$ declare -A associative

Adding key-value pairs

bitarray>declare -A associative

How to retrieve key-values?

bitarray>echo ${associative[key1]}
bitarray>echo ${associative[key2]}
bitarray>echo ${associative[key3]}


How to insert values in a single line?

#dict=([key1]=value1 [key2]=value2 [key3]=value3 ....)### syntax

bitarray>associative=([key1]=1 [key2]=2 [key3]=3)
bitarray>echo ${associative[key3]}


How to get all elements of a dictionary?

bitarray>echo ${associative[@]} #### get all values
3 2 1

bitarray>echo ${associative[*]}  ### get all values
3 2 1

bitarray>echo ${!associative[*]}  ### get all keys
key3 key2 key1


How to delete a key in a dictionary?

bitarray>echo ${!associative[*]}  ### there are three keys
key3 key2 key1
bitarray>unset associative[key1]  ### lets delete key1
bitarray>echo ${!associative[*]}   
key3 key2


Iterate over associative array and print keys- values.

bitarray>for i in ${!associative[@]}; do
> echo $i ${associative[$i]}
> done
key3 3
key2 2