0

I m running bash. I have this:

$ A="This is something"
$ B='$A'
$ echo "$B"
'$A'

So far so good. But then:

$ echo "$(eval $B)"
This: command not found

Which is not what I expected:

This is something

How do I evaluate the string, without executing the result of the evaluation? I only want to perform variable substitution.

EDIT

This works, but is ugly:

A="This is something" ; B='$A' ; eval "echo $B"
blueFast
  • 41,341
  • 63
  • 198
  • 344
  • 1
    `A="This is something"; B=A; echo "${!B}" ` – Jetchisel Nov 11 '21 at 05:04
  • @Jetchisel interesting. Can you explain the `!` and curly brackets syntax? – Andy J Nov 11 '21 at 05:06
  • @Jetchisel you can not change `B`. `B` is most definitely `$A`, as a literal, and comes from outside my script (it is data). You can assume all variables it references (`$A` in this case), are defined in the current shell – blueFast Nov 11 '21 at 05:06
  • @AndyJ, it is called `indirection` – Jetchisel Nov 11 '21 at 05:07
  • `A="This is something"; eval B=\$A; echo "$B"` – Jetchisel Nov 11 '21 at 05:10
  • @Jetchisel. `B` is a given. You can not touch it. `B` is the string `$A` – blueFast Nov 11 '21 at 05:11
  • I cannot touch it? OK, see https://stackoverflow.com/questions/8515411/what-is-indirect-expansion-what-does-var-mean – Jetchisel Nov 11 '21 at 05:12
  • Most of the time indirection can be replace by Associative array (if available), depending on what you're trying to do. – Jetchisel Nov 11 '21 at 05:13
  • Do the answers to [this question](https://stackoverflow.com/questions/69876234/is-it-possible-to-populate-a-variable-in-a-literal-string-using-bash) cover what you're trying to do? (Note: the `envsubst` method would require that the variable(s) be exported.) – Gordon Davisson Nov 11 '21 at 05:17
  • @GordonDavisson unfortunately I am not in control of what variables are referenced, or whether they are exported. I can assume that they are defined in the current shell, but nothing about their export statús – blueFast Nov 11 '21 at 05:53
  • @blueFast You can export them separately from their definition; that is, after `B` is defined as a shell variable (e.g. with `B='$A'`), it can later be exported with `export B`. – Gordon Davisson Nov 11 '21 at 05:58
  • What is ugly is to assign the literal `$A` to `B`instead of just `A`. If you cannot change this one options is to use pattern substitution and indirection: `b="${B#\$}"; echo "${!b}"`. – Renaud Pacalet Nov 11 '21 at 06:54
  • @RenaudPacalet or `declare -n bindedB=${B:1}; echo "$bindedB"` see [my answer about *nameref*](https://stackoverflow.com/a/69924321/1765658) – F. Hauri - Give Up GitHub Nov 11 '21 at 07:11

0 Answers0