is there a way to access an array name dynamically?
the following loop works:
#!/bin/bash
for i in 1 2 3 4 5; do
for j in 1 2 3 4 5; do
state="i=$i, j=$j"
case "$i" in
1) p_1+=("$state");;
2) p_2+=("$state");;
3) p_3+=("$state");;
4) p_4+=("$state");;
5) p_5+=("$state");;
*) break;;
esac
done
done
for i in {0..5}; do echo "${p_1[$i]}"; done
for i in {0..5}; do echo "${p_2[$i]}"; done
for i in {0..5}; do echo "${p_3[$i]}"; done
for i in {0..5}; do echo "${p_4[$i]}"; done
for i in {0..5}; do echo "${p_5[$i]}"; done
The output looks like:
i=1, j=1
i=1, j=2
i=1, j=3
i=1, j=4
i=1, j=5
i=2, j=1
i=2, j=2
i=2, j=3
i=2, j=4
i=2, j=5
i=3, j=1
i=3, j=2
i=3, j=3
i=3, j=4
i=3, j=5
i=4, j=1
i=4, j=2
i=4, j=3
i=4, j=4
i=4, j=5
i=5, j=1
i=5, j=2
i=5, j=3
i=5, j=4
i=5, j=5
But it has that ugly case statement in the middle and is not as flexible as it could be. I would like to be able to expand it without having to expand the case statement.
I tried this:
for i in 1 2 3 4 5; do
for j in 1 2 3 4 5; do
$(p_${i})+=("$i, j=$j") # Does not work
${p_$i}+=("$i, j=$j") # neither does this
done
done
Is there some syntactic magic that would allow me to dynamically define and access array names? Any help is greatly appreciated.
I tried "michas" solution, as shown here:
#!/bin/bash
for i in 1 2 3 4 5; do
for j in 1 2 3 4 5; do
state=("i=$i, j=$j")
eval "p_$i+=($state)"
#also tried
# IFS="_" state=("i=$i,j=$j") #failed to show j=
# IFS="_" eval "p_$i=($state)" # failed to show j=
done
done
for i in {0..5}; do
for j in {0..5}; do
res=p_$i
eval "echo \$p_$i cooked: ${!res}"
#IFS="_" eval "echo \$p_$i cooked: ${!res}" #failed to show j=
done
done
but even with the commented out regions, all returned the following(abridged) output :
i=1, cooked: i=1,
:
i=1, cooked: i=1,
i=1, cooked: i=1,
:
i=3, cooked: i=3,
i=3, cooked: i=3,
:
i=4, cooked: i=4,
i=4, cooked: i=4,
:
i=5, cooked: i=5,
i=5, cooked: i=5,
OK, solved my problem. This loop works as the first ( still limited but now limited to strings without a "+" ) but I can love with that.
#!/bin/bash
for i in 1 2 3 4 5; do
for j in 1 2 3 4 5; do
state=$(echo "i=$i, j=$j" | tr " " "+")
eval "p_$i+=($state)"
done
done
for i in {0..5}; do
for j in {0..5}; do
res=p_$i[$j]
eval "echo ${!res}"| tr '+' ' '
done
done
Thanks!.