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
. Onlystring
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?)
Per the other answers this is the difference between associative (key=value pairs) and indexed (index 0-infinity, value) arrays in Bash.
Now if you want to do a clever trick by building up an indexed array and converting it to an associative array later this is possible, though keep in mind the "values" that get converted to "keys" must be unique in the array or they will get overwritten unless you do some tracking of how many times a given "value" was seen and insert the indices into an array of values for each "key".
https://unix.stackexchange.com/a/177589
You cannot initialize simple index based array declared with
-A
like that.Use this:
OR just:
To use index based indices in an associative array use:
This is declaring an associative array. Note the difference in case,
-a
is used to declare an (indexed) array.declare -a
declares an array indexed by integers.declare -A
declares an associative array indexed by strings.You have to use:
or similar notations to assign to the associative array, and:
to access them.
You have used -A option which is creating associating array variable Instead, you should try creating array variable by using option -a.
bash-3.2$ declare -a BOO
bash-3.2$ BOO=(a b c)
bash-3.2$
bash-3.2$ echo "${BOO[1]}"
b
bash-3.2$ echo "${BOO[2]}"
c
bash-3.2$