Re: Question about associative array runtime assignment vs literal initialization

Félix Hauri via Bug reports for the GNU Bourne Again SHell <[email protected]>
Newsgroups gmane.comp.shells.bash.bugs
Message-ID <[email protected]>
Le Mon, Dec 22, 2025 at 10:20:17AM -0500, Greg Wooledge a écrit :
> The point is NEITHER one of them does what everyone expects.
> 
> hobbit:~$ kv=(one 1 two 2 "two and a half" 2.5 three 3)
> 
> hobbit:~$ declare -A aa=("${kv[@]}"); declare -p aa
> declare -A aa=(["one 1 two 2 two and a half 2.5 three 3"]="" )
> 
> hobbit:~$ declare -A aa="("${kv[@]}")"; declare -p aa
> declare -A aa=([3]="" [a]="half" [two]="and" [2.5]="three" [one]="1" )
> 
> Both of these are "wrong" from the point of view of everybody but Chet.
> It doesn't appear this is going to change.
> 
> The only known workaround is to abandon this approach entirely, and use
> @K plus eval instead.
I'm not sure how to correctly use @K for this!

My solution is to use `%q` of printf and a temporary string:
  $ kv=(one 1 two 2 "two and a half" 2.5 empty '' three 3)
  $ printf -v tmpString '[%q]=%q ' "${kv[@]}"
  $ declare -A "aa=($tmpString)"
  $ declare -p aa
  declare -A aa=([empty]="" [two]="2" ["two and a half"]="2.5" [three]="3" [one]="1" )

-- 
 Félix Hauri  -  <[email protected]>  -  http://www.f-hauri.ch
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.