遍历数组以使用 'find' 的结果分配动态变量

Loop through array to assign dynamic variable with results from 'find'

我正在尝试将 find 的结果分配给动态变量,同时使用数组的条目作为变量名和搜索字符串。

databases=(ABC DEF GHI JKL)
for i in "${databases[@]}"
do
    schema_$i=$(find '/hana/shared/backup_service/backup_shr/Schema' -type d -iname ${i} -mtime 0)
done

结果应该是 0 到 4 个变量,看起来像这样(取决于找到的文件夹数量):

schema_ABC=/hana/shared/backup_service/backup_shr/Schema/ABC

然而,当我尝试这个时,我得到 'No such file or directory' 作为错误。

./find_schema.sh: line 4: schema_ABC=/hana/shared/backup_service/backup_shr/Schema/ABC: No such file or directory
./find_schema.sh: line 4: schema_DEF=/hana/shared/backup_service/backup_shr/Schema/DEF: No such file or directory
./find_schema.sh: line 4: schema_GHI=: command not found
./find_schema.sh: line 4: schema_JKL=/hana/shared/backup_service/backup_shr/Schema/JKL: No such file or directory

文件夹结构如下所示:

Server:/hana/shared/backup_service/backup_shr/Schema # ll
total 0
drwxr-xr-x 2 root root 0 Sep 29  2020 Test
drwxr-xr-x 2 root root 0 Jan 24 21:15 ABC
drwxr-xr-x 2 root root 0 Jan 24 21:30 DEF
drwxr-xr-x 2 root root 0 Jan 12 22:00 GHI
drwxr-xr-x 2 root root 0 Jan 24 21:45 JKL

我认为我没有正确声明该变量,但我无法找出问题所在。

考虑:

schema_$i=$(cmd)

当bash 解析该行时,它首先检查变量赋值。由于 $ 不是变量名中的有效字符,因此它看不到任何变量赋值。然后它将字符串 schema_$i 扩展为字符串 schema_ABC(或者 $i 的当前值是什么)。然后它执行 cmd 以获得一些输出,然后它尝试执行命令 schema_ABC=foo,但找不到与该名称匹配的命令。直觉上,您正试图让 bash 评估字符串 schema_ABC=foo,在这种情况下,您需要使用 eval "schema_$i=$(find ...)" 明确告诉它这样做。但你真的不想去那个兔子洞。

相反,您可以使用关联数组并执行如下操作:

declare -A schema
databases=(ABC DEF GHI JKL)
for i in "${databases[@]}"
do
    schema[$i]=$(...) 
done

声明动态变量名的一种方法是使用declare:

#!/bin/bash

databases=(ABC DEF GHI JKL)
for i in "${databases[@]}"
do
    declare "schema_$i"="$(find '/hana/shared/backup_service/backup_shr/Schema' -type d -iname "$i" -mtime 0)"
done

备注:find命令好像不对;它只会列出名称为“$i”

的目录