【问题标题】:Access bash associate array via variable indirection通过变量间接访问 bash 关联数组
【发布时间】:2019-03-18 07:17:06
【问题描述】:

我希望使用变量访问关联数组。这个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]}"

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

【问题讨论】:

  • 有一个大问题:它创建了一个数字索引数组,而不是关联(字符串索引)数组。由于hellofoo 没有定义,FIRST[hello]FIRST[foo] 都等价于FIRST[0]
  • 正如 Gordon 所说,第二个不起作用:echo "${!alias[foo]}" "${!alias[hello]}" 将输出bar barworld 丢失了。

标签: arrays bash associative


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 2021-12-18
    • 2017-10-14
    • 2014-07-12
    • 1970-01-01
    相关资源
    最近更新 更多