如何通过一个关联数组作为参数传递给bash中的一种功能? [英] How to pass an associative array as argument to a function in Bash?

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

问题描述

如何传递一个关联数组作为参数传递给函数?这是可能的Bash的?

下code未按预期工作:

 功能iterateArray
{
    当地ADATA =$ {@}#关联数组在关键的$ {!ADATA [@]}

    回声键 - $ {}键
    回声值:$ {ADATA [$关键]}DONE}

传递关联数组给函数像普通数组不工作:

  iterateArray$ A_DATA

  iterateArray$ A_DATA [@]


解决方案

我有完全相同的问题,上周想了好一阵子。

看来,该关​​联数组无法序列或复制。有一个很好的Bash FAQ项关联数组其中解释加以详细。最后一节给我的想法如下这对我的作品:

 功能print_array {
    #EVAL串入一个新的assocociative阵列
    EVAL声明-A func_assoc_array =$ {1#* =}
    #证明阵列已成功创建
    声明-p func_assoc_array
}#声明assocociative数组
声明-A assoc_array =([键1] =值1[键2] =值2)
#显示assocociative数组定义
声明-p assoc_array#通过字符串形式assocociative阵列的功能
print_array$(申报-p assoc_array)

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"

or

iterateArray "$A_DATA[@]"

解决方案

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

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 assocociative array
    eval "declare -A func_assoc_array="${1#*=}
    # proof that array was successfully created
    declare -p func_assoc_array
}

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

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

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

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