如何在 Bash 中重命名关联数组? [英] How to rename an associative array in Bash?

查看:25
本文介绍了如何在 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.

须藤代码:

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)

推荐答案

在 bash 中不能直接复制关联数组.正如已经指出的那样,最好的解决方案可能是遍历数组并逐步复制它.

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

这篇关于如何在 Bash 中重命名关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆