On Sun, Mar 24, 2024 at 1:56 PM Greg Wooledge <g...@wooledge.org> wrote:
> It would be pretty reasonable to have a builtin that could take an array > name plus any number of additional argument pairs, and load those pairs > as keys/values into said array. Then you could do something like this: > > declare -A hash=(...) > kvlist=( "${hash[@]@k}" ) > > declare -A newhash > addtoarray newhash "${kvlist[@]}" > > Some readers may observe that this looks a bit like Tcl's "array set" > command. That's not a coincidence. Whenever I see "a list of alternating > keys and values", that's where my mind goes. > > I'm debating mentally whether this hypothetical new builtin would only > work with associative arrays, or also double as an "lappend" (append new > elements to the end of a list/array) if given an indexed array name. > I'm leaning toward having it be both. It wouldn't be any *more* confusing > than the current situation already is. The main difference would be that > with an indexed array, every argument after the array name becomes an > array element, instead of half of them being keys and the other half > being values. > > Then again, I'm not likely to attempt to implement it, so anyone who > actually writes the code gets to make all the decisions. > > The @K transform outputs key value pairs for indexed arrays as well as associative arrays (you used the @k transform which does word splitting and loses the k-v sequence). Thus the @K allows preserving indices in a sparse indexed array. So your hypothetical builtin would only depend on the type of the receiving array. So it wouldn't be every argument as an element - it would still be keys (indices) and values alternating. declare -A hash=(...) kvlist=( "${hash[@]@K}" ) declare -A newhash addtoarray newhash "${kvlist[@]}" declare -a indexed=(...) # or initialized / built up in another way - with sequential or sparse indices kvlist=( "${indexed[@]@K}" ) declare -a newindexed # or omitted addtoarray newindexed "${kvlist[@]}" addtoarray should have options for dealing with index collisions (last wins (default), first wins, error, warning) and a clear before adding would be handy but trivial to do in a script. Another handy but not needed feature would be an option to declare the receiving array and add to it in one go. I'm also unlikely to implement it. -- Visit serverfault.com to get your system administration questions answered.