【问题标题】:Creating and populating nested associative array in bash在 bash 中创建和填充嵌套关联数组
【发布时间】:2017-08-11 08:18:51
【问题描述】:

我想在 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

但它只打印目录中单个文件的信息。

输出如下:

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 -A file_attr 没有创建任何新的关联数组,因此以前的值被覆盖。有肝吗?

【问题讨论】:

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

标签: bash loops multidimensional-array associative-array


【解决方案1】:

您需要在每次循环迭代中创建一个distinctglobal 数组,并将其name 存储在“outer”数组中。您还需要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

【讨论】:

    猜你喜欢
    • 2014-06-20
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 2012-07-31
    • 2014-12-19
    • 2020-07-24
    • 1970-01-01
    相关资源
    最近更新 更多