Bash key value store

 

Bash supports storing key & value pairs with associative arrays.

Associative arrays concept is available only in bash version 4 and above.

With following piece of code I will show how to story key values with associative arrays:

Declare an associative array, here am using keyValues as its name

declare -A keyValues

Assign key1 to val1

keyValues["key1"]=val1

Multiple key value assignments

keyValues+=( ["key2"]=val2 ["key3"]=val3 )

To iterate through each key value

for key in ${!keyValues[@]}
do
  echo ${key} ${keyValues[${key}]}
done

To get specific key’s value

echo ${keyValues[key1]}

By combining all above line my script for key values is following:

#!/bin/bash
declare -A keyValues
keyValues["key1"]=val1
keyValues+=( ["key2"]=val2 ["key3"]=val3 )
for key in ${!keyValues[@]}
do
    echo ${key} ${keyValues[${key}]}
done

echo "Value of key1: "${keyValues[key1]}

Output:
key3 val3
key2 val2
key1 val1
Value of key1: val1

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s