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?
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.
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.
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.
$1 is the first argument (filename1) $2 is the second argument (dir1)
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With