Search code examples
bashassociative-arrayindirection

Bash: append (+=) to nameref (-n) to hash key


In bash 5.0.17,

s='X'; declare -n s2=s
s2+=YYY; declare -p s

correctly yields declare -- s="XYYY". So far so good. Now, what if I make a nameref to an associative array key?

declare -A aa
aa=( [k1]=v1 ); declare -n 'nk1=aa[k1]'
nk1+=YYY; declare -p aa

(I think the quotes are required, since otherwise filename expansion occurs -- test with shopt -s nullglob). This yields

declare -A aa=([k1]="v1aa[k1]YYY" )

Is this syntax for declaring the nameref (or for appending) wrong?


Solution

  • I'm unable to replicate with bash 4.4.20:

    $ declare -A aa=( [k1]=v1 )
    $ declare -n 'nk1=aa[k1]'
    $ nk1+=YYY
    $ declare -p aa
    declare -A aa=([k1]="v1YYY" )
    

    However, on a system with bash 5.1.4, I get declare -A aa=([k1]="v1aa[k1]YYY" ) just like you saw with 5.0.17. So it appears there's a bug that was introduced at some point in the 5.X series.