Bash indirect reference to an associative array

元气小坏坏 提交于 2019-11-29 07:55:37
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
}

Gives:

Jack Ketchum
Clive Barker
Stephen King
H.P. Lovecraft

Since Bash 4.3, declare has a flag -n to define references (this is loosely equivalent to references in C++). This flag tremendously simplifies your problem here:

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

It will be safe if you're having spaces or funny symbols in the keys of your hash (unlike the accepted answer).

John B

From the Bash Reference Guide:

The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).

So you could do this:

fullname()
{
    for first
    do
        echo "$first ${writer[$first]}"
    done
}
fullname "${!writer[@]}"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!