将值添加到以变量命名的关联数组

Adding value to an associative array named after a variable

我正在编写 bash >= 4 脚本,需要您的帮助。

我正在从远程主机检索一些文件以备份它们。 我有一个 for 循环遍历主机并为每个主机测试连接并启动一个检索各种文件的函数。

我的问题是我需要知道什么地方出了问题(如果是),所以我试图将 OK 或 KO 值存储在一个数组中并稍后解析它。

这是代码:

...
for remote_host in $hosts ; do
    short_host=$(echo "$remote_host" | grep -o '^[^.]\+')
    declare -A cluster
    printf "INFO: Testing connectivity to %s...   " "$remote_host"
    if ssh -q "$remote_host" exit ; then
        printf "OK!\n"
        cluster[$short_host]="Reacheable"
        mkdir "$short_host"
        echo "INFO: Collecting files ..." 
        declare -A ${short_host}
        objects1="/etc/krb5.conf /etc/passwd /etc/group /etc/fstab /etc/sudoers /etc/shadow"
        for obj in ${objects1} ; do
            if file_retrieve "$user" "$remote_host" "$obj" ; then
->              ${short_host}=["$obj"]=OK
            else
                ${short_host}=["$obj"]=KO

            fi
        done
...

所以我使用一个名为 cluster 的数组来列出节点是否可访问,另一个数组 - 以节点的短名称命名 - 列出单个文件的 OK 或 KO。 在执行时,我得到了以下错误(第130行是我用上面箭头标记的行)

./test.sh: line 130: ubuntu01=[/etc/krb5.conf]=OK: command not found

我认为这肯定是一个语法错误,但我无法修复它。我尝试了一堆组合但没有成功。

感谢您的帮助。

由于数组名称包含在变量 short_list 中,您需要 eval 才能使赋值生效:

${short_host}=["$obj"]=OK

改为:

eval ${short_host}=["$obj"]=OK
eval ${short_host}=["$obj"]=OK

类似的帖子: