1

Suppose I have a bash variable like this:

tmp1='$(echo foo)'

or

tmp2='`echo foo`'

How to achieve foo as result?

I know that removing the command substitution from the string should work, but is there any other way despite this?

simonmysun
  • 111
  • 3
  • Is the result you want to get a variable called `tmp1` or `tmp2` with the value `foo`? Or do you just want the string `foo` outputted? – Kusalananda Apr 21 '22 at 06:07
  • is there some context here? Why would you have the inner command (the `echo`) wrapped in a command substitution in the first place? Why not e.g. have the command by itself in a variable `a='echo foo'` (but see [here](https://unix.stackexchange.com/q/444946/170373)), or just run the command substitution immediately `b="$(echo foo)"`? – ilkkachu Apr 21 '22 at 07:16
  • 1
    I have my PS1 in this format and I wanted to debug it. The PS1 is in such format because I need it executed everytime. @ilkkachu – simonmysun Apr 21 '22 at 07:57
  • @simonmysun, ah, that makes sense, yes. – ilkkachu Apr 21 '22 at 07:59
  • Getting `foo` as output is enough for me. I only wantted to exam errors inside. @Kusalananda – simonmysun Apr 21 '22 at 07:59

2 Answers2

0

This works:

eval "echo $tmp"

or

bash -c "echo $tmp"

I was told by a friend.

simonmysun
  • 111
  • 3
0

The answer is "don't do this". This is simply not a thing that Bash is designed to do:

http://mywiki.wooledge.org/BashFAQ#BashFAQ.2F050.I.27m_trying_to_put_a_command_in_a_variable.2C_but_the_complex_cases_always_fail.21

dg99
  • 2,641
  • 1
  • 15
  • 21
  • 1
    well, yes, and, well, no. When they have that command substitution somewhere (e.g. in `PS1`), it's already a string, in a variable, and it works just fine. Just that they need to tell the shell to evaluate it as shell syntax, which the shell is perfectly capable of doing, and has a dedicated command for. Not a good idea in general, since it's hard to get right for arbitrary input, but here, it looks like they have a pre-existing command they made themselves, so no untrusted input. – ilkkachu Apr 21 '22 at 08:43