I need to loop over an associative array and drain the contents of it to a temp array (and perform some update to the value).
The leftover contents of the first array should then be discarded and i want to assign the temp array to the original array variable.
Sudo code:
declare -A MAINARRAY
declare -A TEMPARRAY
... populate ${MAINARRAY[...]} ...
while something; do #Drain some values from MAINARRAY to TEMPARRAY
${TEMPARRAY["$name"]}=((${MAINARRAY["$name"]} + $somevalue))
done
... other manipulations to TEMPARRAY ...
unset MAINARRAY #discard left over values that had no update
declare -A MAINARRAY
MAINARRAY=${TEMPARRAY[@]} #assign updated TEMPARRAY back to MAINARRAY (ERROR HERE)
expanding on Luca Borrione's cp_hash - which didn't work for me, and I gave up trying to track down the eval expansion issue - I ran into differences before and after bash 4.2. after 4.2(something) this gets a lot easier... but that's not backwards compatible. See 1 and 2
so my variation tested on 4.1.2(1) and 4.3.46(1):
Copying associative arrays is not directly possible in bash. The best solution probably is, as already been pointed out, to iterate through the array and copy it step by step.
There is another solution which I used to pass variables to functions. You could use the same technique for copying associative arrays:
How about this one (Doesn't create a real copy, just a link to source variable):
Will print:
With associative arrays, I don't believe there's any other method than iterating
Following both the suggestions of glenn jackman and ffeldhaus, you can build a function which might become handy:
Usage:
Example:
Will output