0

I have spent a few hours on this now and can't seem to find a solution.

I have set three associative arrays in code:

template1 template2 template3

This could really be n number of arrays and a counter variable is also set in code so that:

template_name="template$counter"

Would give the next template to create. So my issue is when I want to loop over n number of associative arrays, I need to do something like:

for (( i = 1; i < $counter; i++ )); do
  template_name="template$i"
    for i in ${!template_name[@]}; do
      echo "$i - ${template_name[$i]}"
    done
done

But it does not work - I get bad substitution errors. It seems that I can;t use a variable name to access associative arrays dynamically. Is there any other way to look at this problems ?

1
  • You should either: (1) rethink your design or (2) change language. Doing this stuff in bash is not really advised. Commented Jun 26, 2013 at 7:00

2 Answers 2

1

I found the answer after some more digging:

eval echo "APP_NAME $template_name: "\${${template_name}[APP_NAME]}
Sign up to request clarification or add additional context in comments.

1 Comment

I know - but I am stuck with bash here at work and can't find another method to achieve the outcome I need.
0

I'm not exactly sure if this is want you expected but I think it can help you find a better solution than using eval.

#!/bin/bash
template0=( "123" "456" )
template1=( "zxc" "edc" )

counter=2
for (( i = 0; i != $counter; ++i )); do
    template_name="template$i[@]"
    echo ${!template_name}
    for j in ${!template_name}; do
        echo "$j - template$i"
    done
done

Produces:

==> 123 456
==> 123 - template0
==> 456 - template0
==> zxc edc
==> zxc - template1
==> edc - template1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.