Expand ENV variable of a string, run command and s

2019-03-06 03:29发布

How can I expand a variable, run that command and store output to variable?

Usually you do this

var="$(echo string)"

but I want this

envString='echo $stringToEcho'
stringToEcho="hello world"
var="$(${envString})"` 

but the dollar sign inside doesn't expand. I need to run a command stored in a variable and store the output to another variable.

标签: bash shell
1条回答
仙女界的扛把子
2楼-- · 2019-03-06 03:53

If your string contains content which was written to be eval-safe:

envString="echo string"
var=$(eval "$envString")

...which will work even if it includes variable references, if quoting correctly:

envString='echo "$someVar"'  # use single-quotes here to avoid premature expansion!
someVar='hello world'
var=$(eval "$envString")

However, if your string contains contents generated by expanding variables without using printf %q to safely escape any variables contained, do not do this.


References:

  • BashFAQ #50 ("I'm trying to put a command in a variable, but the complex cases always fail!")
  • BashFAQ #48 ("Eval command and security issues").
查看更多
登录 后发表回答