Bash scripting - Iterating through “variable” variable names for a list of associative arrays

大兔子大兔子 提交于 2019-12-01 05:18:06

The difficulty here stems from the fact that the syntax for indirect expansion (${!nameref}) clashes with the syntax for extracting keys from an associative arrays (${!array[@]}). We can have only one or the other, not both.

Wary as I am about using eval, I cannot see a way around using it to extract the keys of an indirectly referenced associative array:

keyref="queue${count}[@]"
for key in $(eval echo '${!'$keyref'}'); do ... ; done

You can however avoid eval and use indirect expansion when extracting a value from an array given the key. Do note that the [key] suffix must be part of the expansion:

valref="queue${count}[$key]"
echo ${!valref}

To put this in context:

for count in {1..5} ; do
    keyref="queue${count}[@]"
    for key in $(eval echo '${!'$keyref'}'); do
        valref="queue${count}[$key]"
        echo "key = $key"
        echo "value = ${!valref}"
    done
done

I was able to make it work with the following script:

for count in {1..5} ; do
    for key in $(eval echo '${!q'$count'[@]}') ; do
        eval echo '${q'$count"[$key]}"
    done
done

Note it breaks if any key contained a space. If you want to deal with complex data structures, use a more powerful language like Perl.

I think this might work (but untested). The key is to treat the indexing as the full name of a variable. (That is, the array queue5 can be treated as a sequence of variables named queue5[this], queue5[that], etc.)

for count in {1,2,3,4,5} do
    assoc="queue$count[@]"
    for key in "${!assoc}" do
        echo "key : $key"
        val="queue$count[$key]"
        echo "value : ${!val}"
    done
done
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!