0

I am creating a list of arrays in a bash script, per the suggestion in this post- How to declare 2D array in bash (Edit 2 by Sir Athos)-


Edit 2: To declare and initialize a0..a3[0..4] to 0, you could run:

for i in {0..3}; do
    eval "declare -a a$i=( $(for j in {0..4}; do echo 0; done) )"
done

Now I am having difficulty accessing the newly created arrays. I am trying to loop through and recreate the array name the same as they were created, but resulting in 'bad substitution' error.

for j in {0..3}; do
    echo ${a$j[@]:0}
done

error received:

${a$i[@]:0}: bad substitution

Any thoughts on how to access the arrays? Ultimately the list of arrays will be much larger and created dynamically. This is simply an example

1
  • 1
    Which version of bash? 4.3 provides namevars, a far more powerful construct for indirect reference. Commented Mar 18, 2015 at 23:31

1 Answer 1

2

The approach you are using is bad. Use jm666's accepted answer from the same question instead.

With that out of the way:

a1=("foo" "bar")
a2=("baz" "etc")

j=1
var="a$j[@]"
echo "The value of $var is:" "${!var}"

i=0;
var2="a$j[$i]"
echo "The value of $var2 is ${!var2}"

will print

The value of a1[@] is: foo bar
The value of a1[0] is: foo
1
  • Thanks, that did indeed answer the request. I missed the need for indirect variable references. Also I switched to the answer from @jm666 as you noted since it truly makes more sense. Commented Apr 3, 2015 at 23:18

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.