【问题标题】:Dynamic associative arrays动态关联数组
【发布时间】:2021-04-06 03:12:54
【问题描述】:
cert_list=()
env_var=( "lbjk1" "lbjk2" )

for id1 in ${env_var[@]}; do
    declare -A lj_cert
    lj_cert[CONFIG_FILE]="hello_$id1"
    cert_list+=(lj_cert)
done


declare -n cert
for cert in "${cert_list[@]}"; do
    echo ${cert[CONFIG_FILE]}
done

我得到以下输出

hello_lbjk2
hello_lbjk2

但预期的输出是

hello_lbjk1
hello_lbjk2

我哪里错了?

【问题讨论】:

  • 您将hello_$id1 字符串存储在单个位置lj_cert[CONFIG_FILE]。它只能保存一个值。
  • 您能解释一下您的基本目标吗?这似乎相当复杂,我想知道是否有更简单的方法来做你想做的任何事情。
  • 我试图将值存储在上面声明的 cert_list 数组中。我稍后必须将更多值附加到 cert_list。但是现在,只有 hello_lbjk1 和 hello_lbjk2?这可以通过创建动态数组创建来实现吗?比如声明 -A lj_cert_$id1?
  • 你想在更高的层次上做什么?这些值的含义是什么?你在用它们做什么?你有问题X,你认为解决方案是Y;我想知道 X 是什么。见:XY problem
  • 我的目标是使用 declare -A lj_cert_$id1 创建一个动态关联数组,因此我得到两个可以附加到 cert_list 的动态关联数组。这是我唯一的要求。我只需要在现有的代码库中使用它。

标签: bash shell associative-array


【解决方案1】:

我试图解释你的脚本中发生了什么,希望这会有所帮助。

cert_list=()
env_var=( "lbjk1" "lbjk2" )

for id1 in ${env_var[@]}; do
    declare -A lj_cert # move 'declare' out of loop, it's requqired only once    

    lj_cert[CONFIG_FILE]="hello_$id1" # here you are inserting new data
                                      # in the same array item lj_cert[CONFIG_FILE]
                                      # in the end value will be 'hello_lbjk2'

    cert_list+=(lj_cert) # and here you are appending cert_list with the same string 'lj_cert'
done


declare -n cert # from declare help: make NAME a reference to the variable named by its value
for cert in "${cert_list[@]}"; do  # all values in this array are the same 'lj_cert'
    echo ${cert[CONFIG_FILE]}      # 'cert' will always reference to lj_cert, 
done                               # and since index in lj_cert the same (CONFIG_FILE)
                                   # the output is also the same 'hello_lbjk2'

【讨论】:

    【解决方案2】:

    试试下面的shell,看看是否符合要求:

    #!/usr/bin/env bash
    cert_list=()
    env_var=( "lbjk1" "lbjk2" )
    
    for id1 in ${env_var[@]}; do
        declare -A lj_cert
        lj_cert['CONFIG_FILE']="hello_${id1}"
        cert_list+=(${lj_cert[@]})
    done
    
    for cert in "${cert_list[@]}"; do
        echo ${cert[CONFIG_FILE]}
    done
    

    【讨论】:

    • 这毫无意义:cert 将是您代码中的标量,您不能对其使用数组索引。
    猜你喜欢
    • 2017-04-14
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多