2014-03-06 - Bash Associative Arrays
One of the most powerful facilities in bash is the associative array. Such arrays allow arbitrary strings as the subscript indexing each element. Bash documents that one may initialize an associative array by naming the subscript in brackets and assigning the value. That's fine when initializing with constant data, but in several program's written recently the need was for variable data coming from a file. In that case, bash has no direct way to initialize the array because the data read from the file would be in a string variable. That string cannot have the bracketed name because bash won't know the bracket characters are special as part of the string.
Instead, use a loop to parse the string and feed the array data from it. Assume that your string, input, has data in the form:
Instead, use a loop to parse the string and feed the array data from it. Assume that your string, input, has data in the form:
a=1 b=2 c=3
that is, each element is separated by a space from the next element, the indexing name is on the left of the equals sign and the value is on the right, use the following loop to build the associative array:
for str in $input
do
sub="${str%%=*}"
val="${str#*:}"
array["${sub}"]="${val}"
done