In my tutorial,
A Complete Guide On How To Use Bash Arrays, I covered the different type of Bash Arrays available since Bash version >4. When using Associative Arrays, you may improperly declare your Array and get the bash error must use subscript when assigning associative array
. The documentation mention clearly the requirement for the subscript part of the declaration. The subscript part is sometime called a key
or index
in other programming languages.
Arrays are assigned to using compound assignments of the form name=(value1 ... valuen), where each value is of the form [subscript]=string. [...] When assigning to an associative array, the subscript is required.
In short, when using a compound assignment like declare -A array_name=([key1]=value1, [key2]=value2)
, make sure that your shell script properly define the subscript for each key/value pair. The subscript part (key) must be enclosed in square brackets []
and the compound assignment must be properly surrounded by parentheses ()
.
Mistakes as shown below can easily happen if you try to declare programmatically an array while feeding invalid or incomplete data.
# Error
# Missing square brackets [] around the subscript
[me@host ~]$ declare -A myAssociativeArray=(a=123)
bash: myAssociativeArray: a=123: must use subscript when assigning associative array
# Error
# Second assignment is missing square brackets [] around the subscript
[me@host ~]$ declare -A myAssociativeArray=([a]=123 b=456)
bash: myAssociativeArray: b=456: must use subscript when assigning associative array
# Error
# First assignment is missing square brackets [] around the subscript
# Second assignment is missing the subscript
[me@host ~]$ declare -A myAssociativeArray=(a=123 456)
bash: myAssociativeArray: a=123: must use subscript when assigning associative array
bash: myAssociativeArray: 456: must use subscript when assigning associative array
The proper way to declare a Bash Associative Array must include the subscript as seen below.
# Works
[me@host ~]$ declare -A myAssociativeArray
# myAssociativeArray[subscript]=value
[me@host ~]$ myAssociativeArray[a]=123
[me@host ~]$ myAssociativeArray[b]=456
[me@host ~]$ echo ${myAssociativeArray[*]}
456 123
# Works
[me@host ~]$ declare -A myAssociativeArray=([a]=123 [b]=456)
# declare -A myAssociativeArray=([subscript]=value ...)
[me@host ~]$ echo ${myAssociativeArray[*]}
456 123