Bash关联数组并动态分配变量

时间:2022-10-30 12:48:11

I faced with a very strange behavior.

我面对一个非常奇怪的行为。

#!/bin/bash

declare -A array_first=(
    [name]="Array 1"
    [message]="Hi there"
)

declare -A array_second=(
    [name]="Array 2"
    [message]="Bye!"
)

arrays=(array_first array_second)

for arr in ${!arrays[*]}
do
    val=${arrays[$arr]}
    val=${!val}
    echo ${val[name]} # Why this string is empty?
done

echo "${array_first[name]}"
echo "${array_first[message]}"

echo "${array_second[name]}"
echo "${array_second[message]}"

I need the value of an associative array, and displays an empty string. What am I doing wrong?

我需要一个关联数组的值,并显示一个空字符串。我究竟做错了什么?

1 个解决方案

#1


1  

When combining ${!...} with arrays, you have to specify the index or key in the string you evaluate with !:

将$ {!...}与数组组合时,您必须在您评估的字符串中指定索引或键!:

for arr in ${!arrays[*]}
do
    val=${arrays[$arr]}
    ex="$val[name]"
    echo ${!ex} # No longer empty.
done

#1


1  

When combining ${!...} with arrays, you have to specify the index or key in the string you evaluate with !:

将$ {!...}与数组组合时,您必须在您评估的字符串中指定索引或键!:

for arr in ${!arrays[*]}
do
    val=${arrays[$arr]}
    ex="$val[name]"
    echo ${!ex} # No longer empty.
done