Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 910
RKS Avatar asked Jan 17 '13 00:01

RKS


People also ask

How do I use key-value pairs in bash?

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. The above will product the following output.

How do you write a key-value pair?

A key-value pair consists of two related data elements: A key, which is a constant that defines the data set (e.g., gender, color, price), and a value, which is a variable that belongs to the set (e.g., male/female, green, 100). Fully formed, a key-value pair could look like these: gender = male. color = green.

What is $@ in bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What is $1 $2 in bash script?

$1 is the first argument (filename1) $2 is the second argument (dir1)


2 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 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

like image 81
peteches Avatar answered Sep 21 '22 14:09

peteches


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.

like image 27
math Avatar answered Sep 21 '22 14:09

math