在bash中创建和填充嵌套关联数组

在bash中创建和填充嵌套关联数组,bash,loops,multidimensional-array,associative-array,Bash,Loops,Multidimensional Array,Associative Array,我想在bash中创建一个嵌套关联数组,并将其填充到循环中。下面是示例代码,它应该打印所有文件名以及当前目录中该文件的相应上次修改时间 declare -A file_map for file in * do declare -A file_attr uuid=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 16 | head -n 1) file_attr['name']="$file" file_attr['m

我想在bash中创建一个嵌套关联数组,并将其填充到循环中。下面是示例代码,它应该打印所有文件名以及当前目录中该文件的相应上次修改时间

declare -A file_map
for file in *
do
    declare -A file_attr
    uuid=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 16 | head -n 1)
    file_attr['name']="$file"
    file_attr['mod_date']=$(stat -c %y "$file")
    file_map["$uuid"]=file_attr
done


for key in "${!file_map[@]}"
do
    echo $(eval echo \${${file_map[$key]}['name']}) "->" $(eval echo \${${file_map[$key]}['mod_date']})
done
但它只打印目录中单个文件的信息

declare -A file_map
for file in *
do
    declare -A file_attr
    uuid=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 16 | head -n 1)
    file_attr['name']="$file"
    file_attr['mod_date']=$(stat -c %y "$file")
    file_map["$uuid"]=file_attr
done


for key in "${!file_map[@]}"
do
    echo $(eval echo \${${file_map[$key]}['name']}) "->" $(eval echo \${${file_map[$key]}['mod_date']})
done
结果如下:

test.sh -> 2017-03-10 18:46:52.832356165 +0530
test.sh -> 2017-03-10 18:46:52.832356165 +0530
test.sh -> 2017-03-10 18:46:52.832356165 +0530
test.sh -> 2017-03-10 18:46:52.832356165 +0530
而它应该是,
test.sh
和其他3个不同的文件

似乎是
declare-文件\u attr
没有创建任何新的关联数组,因此以前的值被覆盖。任何hep?

您需要在每个循环迭代中创建一个独特的全局数组,并将其名称存储在“外部”数组中。您还需要
declare
来分配给动态生成的数组

declare -A file_map
for file in *
do
    declare -A file_attr$((i++))
    # Consider using something like uuidgen instead
    # uuid=$(uuidgen)
    uuid=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 16 | head -n 1)
    declare -A "file_attr$i[name]=$file"
    declare -A "file_attr$i[mod_date]=$(stat -c %y "$file")"
    file_map[$uuid]="file_attr$i"
done

Use indirect variable expansion, not `eval`, to access the elements.

for uuid in "${!file_map[@]}"
do
    arr=${file_map[$uuid]}
    file_map_name=$arr[name]
    file_map_date=$arr[mod_date]
    echo "$uuid: ${!file_map_name} -> ${!file_map_date}"
done

a{k1}.b{k2}
可以表示为
x{k1.k2}
。散列的平坦化不是更容易吗?只有一个函数在shell中创建一个新的作用域,并且
file\u map[“$uuid”]=file\u attr
只是将字符串“file\u attr”而不是数组引用添加到数组中。我强烈建议使用具有适当数据结构的语言,而不是
bash
。(另外一个好处是,您可能会得到一个封装
stat
系统调用的库,而不必为每个文件运行外部程序。)