Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename an associative array in Bash?

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)
like image 800
David Parks Avatar asked Jul 12 '11 05:07

David Parks


2 Answers

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:

# declare associative array
declare -A assoc_array=(["key1"]="value1" ["key2"]="value2")
# convert associative array to string
assoc_array_string=$(declare -p assoc_array)
# create new associative array from string
eval "declare -A new_assoc_array="${assoc_array_string#*=}
# show array definition
declare -p new_assoc_array
like image 109
Florian Feldhaus Avatar answered Nov 16 '22 20:11

Florian Feldhaus


With associative arrays, I don't believe there's any other method than iterating

for key in "${!TEMPARRAY[@]}"  # make sure you include the quotes there
do
  MAINARRAY["$key"]="${TEMPARRAY["$key"]}"
  # or: MAINARRAY+=( ["$key"]="${TEMPARRAY["$key"]}" )
done
like image 13
glenn jackman Avatar answered Nov 16 '22 19:11

glenn jackman