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

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

然后应该丢弃第一个数组的剩余内容,我想将temp数组分配给原始数组变量.

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代码:

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)

推荐答案

对于关联数组,我认为除了迭代之外没有其他方法

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

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

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