Expand ENV variable of a string, run command and store in variable?

后端 未结 1 571
故里飘歌
故里飘歌 2021-01-25 21:36

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

相关标签:
1条回答
  • 2021-01-25 22:15

    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").
    0 讨论(0)
提交回复
热议问题