Search code examples
arraysbashassociative-array

Bash array assignment fails if you declare the array in advance


This works:

$ BAR=(a b c)
$ echo "${BAR[1]}"
b

This, however, doesn't:

$ declare -A FOO
$ FOO=(a b c)
bash: FOO: a: must use subscript when assigning associative array
bash: FOO: b: must use subscript when assigning associative array
bash: FOO: c: must use subscript when assigning associative array

The docs claim the subscript is optional:

Arrays are assigned to using compound assignments of the form name=(value1 ... valuen), where each value is of the form [subscript]=string. Only string is required.

What about the use of declare changes the syntax of array assignment here? Why does hinting bash about the type of the variable with declare change things? (Why does declare exist at all — if I assign an array to a variable, then the variable is an array… no?)


Solution

  • declare -a declares an array indexed by integers.

    declare -A declares an associative array indexed by strings.

    You have to use:

    FOO=([1]="a" [2 or 3]="b or c")
    

    or similar notations to assign to the associative array, and:

    echo "${FOO[2 or 3]}"
    

    to access them.