Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

variables

bash

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?

like image 373
Hao Shen Avatar asked Aug 14 '13 03:08

Hao Shen


People also ask

How do I reference a variable in bash?

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.

What does $_ mean in bash?

$_ (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. $@

How do you call a variable from another shell script?

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.


3 Answers

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.

like image 66
Vaughn Cato Avatar answered Sep 30 '22 04:09

Vaughn Cato


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}
like image 39
jxh Avatar answered Sep 30 '22 04:09

jxh


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.

like image 27
David W. Avatar answered Sep 30 '22 05:09

David W.