通过变量间接访问 bash 关联数组

Access bash associate array via variable indirection

我希望使用变量访问关联数组。这个 post 的已接受答案中的示例正是我想要的:

$ declare -A FIRST=( [hello]=world [foo]=bar )
$ alias=FIRST
$ echo "${!alias[foo]}"

然而,当我使用 bash 4.3.48 或 bash 3.2.57 时,这对我不起作用。 但是,如果我不声明 ("declare -A") 数组,它确实有效,即这有效:

$ FIRST[hello]=world 
$ FIRST[foo]=bar
$ alias=FIRST
$ echo "${!alias[foo]}"

不声明数组有什么问题吗?

正如预期的那样工作,您只是错过了定义更多级别的间接访问值,

declare -A first=()
first[hello]=world 
first[foo]=bar
alias=first
echo "${!alias[foo]}"     

上面的结果显然是空的,因为另一个答案指出,因为还没有创建对数组键的引用。现在定义一个 item 来引入第二层间接引用以指出实际的 key 值。

item=${alias}[foo]
echo "${!item}"
foo

现在将项目指向下一个键hello

item=${alias}[hello]
echo "${!item}"
world

或者更详细的示例是,运行 对关联数组的键进行循环

# Loop over the keys of the array, 'item' would contain 'hello', 'foo'
for item in "${!first[@]}"; do    
    # Create a second-level indirect reference to point to the key value
    # "$item" contains the key name 
    iref=${alias}["$item"]
    # Access the value from the reference created
    echo "${!iref}"
done