Bash对关联数组的间接引用 [英] Bash indirect reference to an associative array

查看:89
本文介绍了Bash对关联数组的间接引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个非常简化的示例中,我需要处理数组元素的键和值:

In this very simplified example, I need to address both key and value of an array element:

declare -A writer
writer[H.P.]=Lovecraft
writer[Stephen]=King
writer[Clive]=Barker
writer[Jack]=Ketchum

for i in ${!writer[@]}
do
    echo "$i ${writer[$i]}"
done

fullname()
{
    pointer=$1[@]
    for i in "${!pointer}"
    do
        echo "? $i"
    done
}
fullname writer

该函数必须以与示例循环相同的格式显示输出,并且该函数应该接收数组名,键列表或值,而我尝试了所有这些操作,但均未成功.任何建议都将不胜感激.

The function must display the output in the same format as the example loop before it, and it should receive either array name, list of keys or values, all of which I tried, without success. Any suggestions are greatly appreciated.

推荐答案

indir_keys() {
    eval "echo \${!$1[@]}"
}

indir_val() {
    eval "echo \${$1[$2]}"
}

fullname()
{
    pointer=$1
    for i in $(indir_keys $pointer)
    do  
        echo "$i $(indir_val $pointer $i)"
    done
}

给予:

Jack Ketchum
Clive Barker
Stephen King
H.P. Lovecraft

这篇关于Bash对关联数组的间接引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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