Bash scripting - Iterating using variable names for a list of associative arrays

I have a list of associative array variables that I want to iterate over and retrieve their key / value pairs.

I iterate over one associative array, listing all its keys and getting the values, i.e.

for key in "${!queue1[@]}" do echo "key : $key" echo "value : ${queue1[$key]}" done 

The tricky part is that associative array names are variable variables, for example. given count = 5, associative arrays will be called queue1, queue2, queue3, queue4, queue5.

I am trying to replace the above sequence based on a count, but so far each combination of parentheses and eval has not produced much more errors with a bad replacement. for example below:

 for count in {1,2,3,4,5} do for key in "${!queue${count}[@]}" do echo "key : $key" echo "value : ${queue${count}[$key]}" done done 

Help would be greatly appreciated!

+6
source share
3 answers

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

Caution, since I am using eval , I see no way to use it to retrieve the keys of an indirect reference array:

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

However, you can avoid eval and use an indirect extension when retrieving a value from an array based on the key. Note that the [key] suffix must be part of the extension:

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

For this, in the context of:

 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 
+3
source

I managed to get it to 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 

Please note that it is interrupted if any key contains a space. If you want to deal with complex data structures, use a more powerful language like Perl.

+1
source

I think this might work (but not verified). The key is to handle indexing as the full name of the variable. (That is, the queue5 array can be processed 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 
0
source

All Articles