How can I use as a sequence of alternating keys and values to define a Bash 5.1 associative array?

Viewed 136

I read in the release notes of Bash 5.1:

gg. Associative arrays may be assigned using a list of key-value pairs within a compound assignment. Compound assignments where the words are not of the form [key]=value are assumed to be key-value assignments. A missing or empty key is an error; a missing value is treated as NULL. Assignments may not mix the two forms.

Checking on the Bash 5.1 Reference Manual → Arrays section I see this new block (comparing to the Bash 4.4 Reference Manual):

When assigning to an associative array, the words in a compound assignment may be either assignment statements, for which the subscript is required, or a list of words that is interpreted as a sequence of alternating keys and values: name=(key1 value1 key2 value2 … ). These are treated identically to name=( [key1]=value1 [key2]=value2 … ). The first word in the list determines how the remaining words are interpreted; all assignments in a list must be of the same type. When using key/value pairs, the keys may not be missing or empty; a final missing value is treated like the empty string.

This syntax is also accepted by the declare builtin. Individual array elements may be assigned to using the name[subscript]=value syntax introduced above.

So I did a test:

$ bash --version
GNU bash, version 5.1.0(1)-release (x86_64-apple-darwin18.5.0)
$ declare -a bla
$ bla=( [name]=me )
$ echo "${bla[name]}"
me      # it works well

However, if I use the new syntax it does not work to me and it returns me the key instead of the value:

$ declare -a bla
$ ble=( name me )
$ echo "${ble[name]}"
name      # should be "me"

How can I properly use the compound assignment as a sequence of alternating keys and values?

1 Answers

It is a matter of defining the associative array with declare -A (note the capital letter for "A"):

declare -A bla
$ bla=(k1 v1 k2 v2)
$ echo "${bla[k1]}"
v1

If you try to mix assignations, it fails as indicated:

$ bla=([k1]=v1 k2 v2)
bash: bla: k2: must use subscript when assigning associative array
bash: bla: v2: must use subscript when assigning associative array
$ bla=([k1]=v1 [k2]=v2)
$ echo "${bla[k2]}"
v2
Related