Re: Question about associative array runtime assignment vs literal initialization

Greg Wooledge <[email protected]>
Newsgroups gmane.comp.shells.bash.bugs
Message-ID <[email protected]>
On Mon, Dec 22, 2025 at 20:21:57 +0100, Félix Hauri via Bug reports for the GNU Bourne Again SHell wrote:
>   $ declare -A aa=( empty '' inject '$(date)' "space key" "space value"  \
>         '$(uptime)' injected  lb \[ rb \] punc $' \t\n' )
>   $ printf -v tmpString '["%s"]="%s" ' "${aa[@]@k}"
>   $ declare -A "newarray=($tmpString)"
>   $ declare -p newarray
>   declare -A newarray=([inject]="Mon Dec 22 20:16:59 CET 2025" [lb]="[" ["space ke
>   y"]="space value" [empty]="" [punc]=$' \t\n' [rb]="]" [" 20:16:59 up 1 days, 10:
>   18, 1 users,  load average: 0.18, 0.12, 0.23"]="injected" )

So you've discovered a way that *doesn't* work.  Congratulations.  Now
don't use that.

So far, the ways we've discovered that *do* seem to work are:

 1) printf -v string '[%q]=%q ' "${aa[@]@k}"; declare -A "new=($string)"

 2) string="${aa[*]@K}"; eval declare -A "new=($string)"

 3) list=("${aa[@]@k}"); eval declare -A "new=(${list[*]@Q})"

The first two serialize the associative array as a string (two different
strings).  The third one dumps the array to a list, then serializes that
list as a (transient) string.

There is no known way to reconstruct an associative array directly from
a list, without first converting that list to a string.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.