user2051785
user2051785

Reputation: 3

How to loop through a list of arrays, created in the bash script

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

Upvotes: 0

Views: 114

Answers (1)

that other guy
that other guy

Reputation: 123460

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

Upvotes: 2

Related Questions