0

I'm trying to figure out the proper way to expand a variable within a string and in quotes when I want it done.

Here's some of the code:

LABEL="-run_label \"\$STATUS\""

#some stuff done here

STATUS="We_re running something now..."

POSTFIX="<command_call> other_args $LABEL"

Unfortunately if I do an $(eval echo $POSTFIX) and save that to a variable the result is something like

<command_call> other_args -run_label We_re running something now... and it blows up because it doesn't recognize arguments "running", "something", "now..."

So I've tried to set LABEL="-run_label \\\"\$STATUS\\\"" then run $(eval echo $POSTFIX)

but now it's <command_call> other_args -run_label '"We_re' 'running' 'something' 'now..."' and it again complains that 'running' 'something' 'now...' are not valid arguments.

What am I doing wrong to expand these variables in a string inside a quote block (can be single or double quote) at a later time when I need it to be called?

Edit: I'm not using that exact string so removed the ' as I realized it would complain and moved to _

Eddie
  • 1
  • 2
  • 2
    If you want to store some code to run at a later time, you should use a function and not a string. If you want to build a list of arguments, you should use an array and not a string. – that other guy Oct 10 '19 at 04:10
  • Unfortunately it's mixed in with different code from different sources. I can only inject the LABEL value and the POSTFIX is processed elsewhere outside of my code. So hence the reason to do it this way. I can only adjust LABEL and STATUS as it evals the POSTFIX – Eddie Oct 10 '19 at 04:38
  • 1
    Any solution that requires `eval` should be avoided. See ["Why should eval be avoided in Bash, and what should I use instead?"](https://stackoverflow.com/questions/17529220/why-should-eval-be-avoided-in-bash-and-what-should-i-use-instead) and also [Eval command and security issues](http://mywiki.wooledge.org/BashFAQ/048). – John1024 Oct 10 '19 at 05:59
  • 1
    Trying to create a command string -- as a variable, or by `echo`, or whatever -- is pretty much always a mistake. Depending on exactly what you're trying to do, either a function or an array is almost always better. See [BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!](http://mywiki.wooledge.org/BashFAQ/050) – Gordon Davisson Oct 10 '19 at 06:10
  • 1
    ...Or just run the command directly, without trying to store it first. Is there any reason you can't just run ` other_args -run_label "$STATUS"`? – Gordon Davisson Oct 10 '19 at 06:15

0 Answers0