How to use a key-value dictionary in bash

Last updated on February 22, 2021 by Dan Nanni

In any programming language, a dictionary is one of the most fundamental data structures that can store a set of objects. In a dictionary, objects are stored in the form of <key, value> pairs. That is, a dictionary stores a set of keys, and each key has a value associated with it. You can insert, retrieve or update a value in a dictionary by using its corresponding key. The dictionary data structure is optimized for fast retrieval of values based on their keys, so it is often implemented with hash tables. In different programming languages, a dictionary is often called by different names, such as associative array, hashmap, or just map.

While bash is not a general-purpose programming language, bash version 4 and higher supports dictionaries or associative arrays natively. In this tutorial, I demonstrate how you can use a key-value dictionary in bash. To help you understand better, I illustrate detailed usages of a dictionary using shell script examples.

Declare a Dictionary Variable in Bash

Variables in bash are not strongly typed. For example, a given bash variable can be treated as strings or integers. But you can enforce type-like behavior in bash by declaring an "attribute" of a variable. One of supported attributes is associative array. So when you want to use a dictionary in bash, use declare statement with -A option (meaning "associative array") to declare a dictionary variable.

declare -A test_var

With this statement, test_var variable can only be used as a dictionary.

Add Key-Value Pairs in a Dictionary in Bash

If you want to add <key, value> pairs to a dictionary, refer to the following examples.

# add key/value string literals without quote
test_var[key1]=value1

# add key/value string literals with quote
test_var['key2']='value2'

# add key/value pair using bash variables
another_key_var='key3'
another_value_var='value3'
test_var[$another_key_var]=$another_value_var

Retrieve Key-Value Pairs from a Dictionary in Bash

If you want to look up a dictionary with a key and retrieve a corresponding value, you have to add $ sign with braces to a dictionary variable. The following shell script snippet is continuation from the previous example.

echo ${test_var[key1]}
echo ${test_var[key2]}
echo ${test_var[$another_key_var]}

The above will product the following output.

value1
value2
value3

Update an Existing Key-Value in a Dictionary in Bash

Updating an existing key-value (i.e., changing the value for an existing key) is no different from inserting a new key-value pair in terms of syntax. With update, the existing value is simply overwritten with a new value.

test_var[key1]='another_value1'

Check if a Key Exists in a Dictionary in Bash

Sometimes you want to check whether or not a key is stored in a dictionary. You can test the existence of a key in a dictionary by checking if its corresponding value is set (use -v operator in a conditional).

if [ -v test_var[key1] ]; then
    echo "key1 exists in a dictionary"
fi

if [ ! -v test_var[key2] ]; then
    echo "key2 does not exists in a dictionary"
fi

Remove a Key-Value Pair from a Dictionary in Bash

You can delete an existing key-value pair from a dictionary by specifying a key in the unset statement.

unset test_var[key1]
unset test_var['key2']
unset test_var[$another_key_var]

Iterate a Dictionary in Bash

Another commonly used feature is dictionary iteration, i.e., iterate over all key-value pairs stored in a dictionary and perform some actions. You can use the following for loop for dictionary iteration in bash. Note that you need to surround the ${!test_var[@]} variable in the loop with "quotes" to safely handle the keys which contain spaces.

for key in "${!test_var[@]}"; do
    echo "$key ${test_var[$key]}"
done
value1
value2
value3

If you find this tutorial helpful, I recommend you check out the series of bash shell scripting tutorials provided by Xmodulo.

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal (Credit Card) or Bitcoin (1M161JGAkz3oaHNvTiPFjNYkeABox8rb4g).

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean