展开字符串的ENV变量,运行命令并存储在变量中? [英] Expand ENV variable of a string, run command and store in variable?

查看:70
本文介绍了展开字符串的ENV变量,运行命令并存储在变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何扩展变量,运行该命令并将输出存储到变量?

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

通常您会这样做

var="$(echo string)"

但是我想要这个

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.

推荐答案

如果您的字符串包含被编写为eval安全的内容:

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")

但是,如果您的字符串包含通过扩展变量而未使用printf %q安全地转义包含的任何变量而生成的内容,则请勿这样做.

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

参考:

  • BashFAQ#50 (我正在尝试将命令放入变量中,但是复杂的案例总是失败!)
  • BashFAQ#48 (评估命令和安全性问题").
  • 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").

这篇关于展开字符串的ENV变量,运行命令并存储在变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆