Is there a way to create key-value pairs in Bash script?
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
).
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