Indirect variables in Bash

Hello,
I've spent hours this morning reading various past forum posts and documentation pages but I can't find exactly what I need.

I'm trying to call a variable with a variable in the name without having to make a third variable.

For example:

path=AB
legAB=50

leg$path 

I want to be able to call leg$path variable and get the value "50"

I am aware that if I created another variable I could do this using the ${! } notation:

var=leg$path
echo ${!var}=50

However, I want to be able to miss out this last step. Is this possible?
Thanks,
Dan

A not-recommended way:

eval echo \$leg$path

By the way, I think you meant echo ${!var} instead of echo ${!leg} .

1 Like

Hi,
Yep, that works. Why is it not recommended?

You were right, I made a mistake in the original post but it has now been changed.

Because if $path is obtained from user input or an input file, or otherwise not under your control someone could execute code with the permissions of the person executing the script.

If you are using bash 4 or you could switch to ksh93 then an alternative might be associative arrays:

leg=([AB]=50 [CD]=40)
echo "${leg[AB]}"
1 Like

This is easiest done with read. It's handy because it takes a variable name, which you can construct by any means you want.

 read $A$B <<<"string"
2 Likes

Thanks Scrutinizer and Corona. However, how do you implement "read" to do this? I've been playing with it and reading about it but can't find anything about this usage.

Kind of exactly how I've shown you.

A="abc"
B="def"

read $A$B <<<"string"

...should put the string "string" into the variable named abcdef.

This is how it's often used:

read VARNAME

...but note that it takes a variable name -- a string -- not the variable itself. You can feed it whatever string you please, derived from whatever variables you please, and do things that would otherwise require ugly insecure eval hacks.

You can redirect into it any way you please. <<< is an ordinary redirection in BASH which replaces stdin with a string.

2 Likes

Hi,
I understand this now and it works perfectly. Thank you very much.

But this method would also have its security risks, but on the left hand side, no? One must control the contents of variables A and B...
*edit* To elaborate: I came across this page

The same applies to the read $var construct. I tried this also in ksh93 and then there is an error message ( arithmetic syntax error ) and the code does not get executed..