'Is there a way to create key-value pairs in Bash script?

I am trying to create a dictionary of key value pair using Bash script. I am trying using this logic:

declare -d dictionary
defaults write "$dictionary" key -string "$value"

...where $dictionary is a variable, but this is not working.

Is there a way to create key-value pairs in Bash script?



Solution 1:[1]

If you can use a simple delimiter, a very simple oneliner is this:

for i in a,b c_s,d ; do 
  KEY=${i%,*};
  VAL=${i#*,};
  echo $KEY" XX "$VAL;
done

Hereby i is filled with character sequences like "a,b" and "c_s,d". each separated by spaces. After the do we use parameter substitution to extract the part before the comma , and the part after it.

Solution 2:[2]

In bash, we use

declare -A name_of_dictonary_variable

so that Bash understands it is a dictionary.

For e.g. you want to create sounds dictionary then,

declare -A sounds

sounds[dog]="Bark"

sounds[wolf]="Howl"

where dog and wolf are "keys", and Bark and Howl are "values".

You can access all values using : echo ${sounds[@]} OR echo ${sounds[*]}

You can access all keys only using: echo ${!sounds[@]}

And if you want any value for a particular key, you can use:

${sounds[dog]}

this will give you value (Bark) for key (dog).

Solution 3:[3]

For persistent key/value storage, you can use kv-bash, a pure bash implementation of key/value database available at https://github.com/damphat/kv-bash

Usage

git clone https://github.com/damphat/kv-bash
source kv-bash/kv-bash

Try create some permanent variables

kvset myName  xyz
kvset myEmail [email protected]

#read the varible
kvget myEmail

#you can also use in another script with $(kvget keyname)
echo $(kvget myEmail)

Solution 4:[4]

Using an example above this is what I did

#!/bin/sh
lookup_vht_index() {
for i in VHT20,0 VHT40,1 VHT80,2 VHT160,3 ; do
  KEY=${i%,*};
  VAL=${i#*,};
#  echo $KEY" XX "$VAL;
  [ "$1" = "$KEY" ] && echo $VAL
done
}

lookup_vht_name() {
for i in 0,VHT20 1,VHT40 2,VHT80 3,VHT160 ; do
  KEY=${i%,*};
  VAL=${i#*,};
#  echo $KEY" XX "$VAL;
  [ "$1" = "$KEY" ] && echo $VAL
done
}


echo "VHT20="$(lookup_vht_index "VHT20")
echo "2="$(lookup_vht_name 2)

Solution 5:[5]

in older bash (or in sh) that does not support declare -A, following style can be used to emulate key/value

# key
env=staging


# values
image_dev=gcr.io/abc/dev
image_staging=gcr.io/abc/stage
image_production=gcr.io/abc/stable

img_var_name=image_$env

# active_image=${!var_name}
active_image=$(eval "echo \$$img_var_name")

echo $active_image

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 yunque
Solution 2 andrej
Solution 3 Pineda
Solution 4 Craig
Solution 5