如何将关联数组作为参数传递给 Bash 中的函数? [英] How to pass an associative array as argument to a function in Bash?

查看:33
本文介绍了如何将关联数组作为参数传递给 Bash 中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将关联数组作为参数传递给函数?这在 Bash 中可行吗?

How do you pass an associative array as an argument to a function? Is this possible in Bash?

下面的代码没有按预期工作:

The code below is not working as expected:

function iterateArray
{
    local ADATA="${@}"            # associative array

for key in "${!ADATA[@]}"
do
    echo "key - ${key}"
    echo "value: ${ADATA[$key]}"

done

}

像普通数组一样将关联数组传递给函数不起作用:

Passing associative arrays to a function like normal arrays does not work:

iterateArray "$A_DATA"

iterateArray "$A_DATA[@]"

推荐答案

我上周遇到了完全相同的问题,并考虑了很长时间.

I had exactly the same problem last week and thought about it for quite a while.

看来,关联数组不能被序列化或复制.有一个很好的 Bash FAQ 条目,用于关联数组,详细解释了它们.最后一部分给了我以下对我有用的想法:

It seems, that associative arrays can't be serialized or copied. There's a good Bash FAQ entry to associative arrays which explains them in detail. The last section gave me the following idea which works for me:

function print_array {
    # eval string into a new associative array
    eval "declare -A func_assoc_array="${1#*=}
    # proof that array was successfully created
    declare -p func_assoc_array
}

# declare an associative array
declare -A assoc_array=(["key1"]="value1" ["key2"]="value2")
# show associative array definition
declare -p assoc_array

# pass associative array in string form to function
print_array "$(declare -p assoc_array)" 

这篇关于如何将关联数组作为参数传递给 Bash 中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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