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?
Example 28-1. Indirect referencing in Bash is a multi-step process. First, take the name of a variable: varname. Then, reference it: $varname. Then, reference the reference: $$varname.
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails. $@
You have basically two options: Make the variable an environment variable ( export TESTVARIABLE ) before executing the 2nd script. Source the 2nd script, i.e. . test2.sh and it will run in the same shell.
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.
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}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With