2

I am trying to dereference two or more variables contained in a single variable but I can't think of how to do it without eval:

$:b=5
$:c=10
$:a='$b $c'
$:result=`eval echo $a`
$:echo $result
5 10

I'm looking to do the equivalent operation that gives me 'result' so I don't have to do an eval. Is it possible to resolve multiple variables referenced by a single variable any other way? I'm looking to do this in BASH

fthinker
  • 646
  • 2
  • 9
  • 17
  • 1
    no it's not possible. and eval is dangerous, be cautious. any reason to do this?? – Karoly Horvath Feb 17 '12 at 17:02
  • I maintain a script that dereferences environment variables that contain variables within the script. It is not clear whether the environment vars will always include variables. For instance on one evocation the var INPUT="once upon a time" and at another it may contain INPUT="once upon a time there was a $ladname" where $ladname may or may not exist in the script that I maintain. This is the complicated answer to your question and it isn't all that relevant :) – fthinker Feb 17 '12 at 19:09

2 Answers2

4

In short, no I think that you have to use an eval for multi-variable indirect references as you have in your code.

There appear to be two types of indirect variable reference in Bash, one with eval and one with the special notation ${!var}:

$ b=5
$ a=b
$ echo ${!a}
5

Perhaps using an array would meet your needs:

$ b=5
$ c=10
$ a=(b c)
$ echo ${!a[0]} ${!a[1]}
5 10

http://tldp.org/LDP/abs/html/abs-guide.html#IVR

kwarrick
  • 5,930
  • 2
  • 26
  • 22
1

eval sound quite scary...

here is a better solution:

Bash Templating: How to build configuration files from templates with Bash?

you just have to tweak it a bit so it follows your syntax.

Community
  • 1
  • 1
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • I like the perl solution there as it doesn't use eval. Also you may notice that I did raise this question in the first place because I was unsatisfied with eval ;) Thanks. – fthinker Feb 17 '12 at 19:29