[bash] 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?

This question is related to bash shell associative-array

The answer is


In bash version 4 associative arrays were introduced.

declare -A arr

arr["key1"]=val1

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

The arr array now contains the three key value pairs. Bash is fairly limited what you can do with them though, no sorting or popping etc.

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

Will loop over all key values and echo them out.

Note: Bash 4 does not come with Mac OS X because of its GPLv3 license; you have to download and install it. For more on that see here


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)

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

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.


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).


Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to associative-array

How to insert a new key value pair in array in php? Rename a dictionary key How to update specific key's value in an associative array in PHP? Is there a way to create key-value pairs in Bash script? PHP combine two associative arrays into one array Are there dictionaries in php? Display array values in PHP Adding an item to an associative array Extract subset of key-value pairs from Python dictionary object? Java associative-array