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

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

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

... where $dictionary is a variable, but this does not work.

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

+43
bash shell
Jan 17 '13 at 0:05
source share
3 answers

In bash version 4, associative arrays were introduced.

 declare -A arr arr["key1"]=val1 arr+=( ["key2"]=val2 ["key3"]=val3 ) 

The arr array now contains three pairs of key values. bash is pretty limited what you can do with them, but not sort or pop up, etc.

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

Flip all the key values ​​and send them.

+90
Jan 17 '13 at 1:54
source share

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

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

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

+23
May 16 '14 at
source share

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

Using

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

Try creating some constant variables

 kvset myName xyz kvset myEmail xyz@example.com #read the varible kvget myEmail #you can also use in another script with $(kvget keyname) echo $(kvget myEmail) 
+3
Mar 04 '15 at 2:03
source share



All Articles