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

问题描述 投票:1回答:1

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

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

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

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

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

arrays bash associative
1个回答
1
投票

它工作正常,您只是错过了定义一个更多级别的间接访问该值,

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
© www.soinside.com 2019 - 2024. All rights reserved.