i need to combine ARRAY1 and ARRAY2 into an associative array like ARRAY. i'm using this code:

 mapfile -t ARRAY1 < <(/bin/awk '{ print $ 1 }' /output/gen_branch)
 mapfile -t ARRAY2 < <(/bin/awk '{ print $ 6 }' /output/gen_code )
 declare -A ARRAY

 for ((i=0; $i<${#ARRAY1[@]}; i++))
 ARRAY+=( ["${ARRAY1[i]}"] = "${ARRAY2[i]}" )

 ##added this loop to check output
 for value in "${!ARRAY[@]}"
 echo "branch: $value"
 echo "code: ${ARRAY[$value]}"

i expect something like this to use them in other parts of bash (it is important that the value of first element of ARRAY1 be the first element of ARRAY2 and so on) :

ARRAY1=( b1 b2 b3 )
ARRAY2=( c1 c2 c3 )
ARRAY= ( [b1]=c1 [b2]=c2 [b3]=c3 ) 

but when i run my code i get this error:

line 7: ARRAY: [b1]: must use subscript when assigning associative array
line 7: ARRAY: =: must use subscript when assigning associative array
line 7: ARRAY: c1: must use subscript when assigning associative array
(and it goes on like this for every entry)  

i think i'm doing it all wrong on line 7.what should i do to fix this?

  • 1
    Remove spaces around =
    – muru
    Sep 15, 2019 at 5:34
  • @muru it worked. would you like to turn it into an answer so i can accept it? Sep 15, 2019 at 5:36
  • 1
    Why not do the whole thing in awk? Sep 15, 2019 at 7:16
  • 1
    @Kusalananda, $ is an operator like any other in awk, there's no problem having spaces around it, not any more than around + or *. Sep 15, 2019 at 8:59
  • 1
    awk is a tool designed for text processing and with associative array support and is much more efficient at it than a shell. So, unless you need to run some commands on the elements of that associative array (a shell is the tool to run other commands, awk does invoke a shell to run other commands for instance), it would make more sense to use awk. Sep 15, 2019 at 9:01

1 Answer 1


There must not be spaces around the =.



would be more legible IMO.

For the record, in zsh, to turn two arrays into an associative array/hash, you'd do:

typeset -A hash

Where ${array1:^array2} is the array zipping operator and the @ parameter expansion flag is used to preserve empty elements (in double quotes, similar to "$@"). (by the way, bash hashes don't support empty keys).

  • Note that ordering of keys is not guaranteed by eg bash Sep 15, 2019 at 18:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .