Hao Shen
Hao Shen

Reputation: 2755

In bash, how to use a variable as part of the name of another variable?

Just a simple question

I have some arrays:

array_0=(1 2 3) 
array_1=(1 2 3) 
.......

I have a variable a:

 a=0
 echo ${array_"$a"[0]}

Got a bad substitution error. Does anyone know the right syntax?

Upvotes: 5

Views: 1151

Answers (3)

jxh
jxh

Reputation: 70502

You can use eval:

#!/bin/bash
array_0=(1 2 3)
array_1=(4 5 6)
array_2=(7 8 9)
for a in {0..2} ; do
  for i in {0..2} ; do
    eval 'echo ${'"array_$a[$i]"'}'
  done
done

Vaughn Cato's syntax is slightly more verbose, but the echo statement itself is more decipherable. You replace the inner part of the double for loop with these two lines:

    array_a=array_$a[$i]
    echo ${!array_a}

Upvotes: 1

Vaughn Cato
Vaughn Cato

Reputation: 64308

One thing you can do is to use this syntax:

array_a=array_$a[0]
echo ${!array_a}

The ! as the first character indicates that you want to use an extra level of indirection by evaluating the variable and then using the result as the expression.

Upvotes: 5

David W.
David W.

Reputation: 107090

You can use eval

echo $(eval echo \${array_$a[0]})

Note that I had to put a backslash in front of the first dollar sign to prevent the shell from interpolating that.

Needless to say, the whole purpose of arrays is to allow you to do this type of variable interpolation without all the fuss and bother of echoing evals like I had to do when I needed arrays with the original Bourne shell.

Upvotes: 1

Related Questions