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 18:04:22 +0100, Félix Hauri via Bug reports for the GNU Bourne Again SHell wrote:
> 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" )

That seems to work, yes, though I only tested it briefly.

> I'm not sure how to correctly use @K for this!

Your solution begins with a list of alternating keys and values.  @K helps
when you're starting with an associative array instead of a list, and
you use it with eval:

    declare -A aa=( empty '' inject '$(date)' "space key" "space value" \
        lb \[ rb \] punc $' \t\n' )
    kvstring="${aa[*]@K}"
    eval "declare -A newarray=($kvstring)"

Here, you don't create a list of keys and values at all.  You go straight
from the associative array to a serialized string value.
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.