我在内存中有一个字符串,分配给一个 bash 变量,其中包含占位符。我想替换环境中使用变量的那些。
例如
#!/bin/bash
MYSTRING='Hello, ${FOO}'
export FOO="world!"
REPLACED=$(how?${MYSTRING})
echo "${REPLACED}"
# should return Hello, world!
我需要的是这部分 $(how?${MYSTRING})
(我是唯一会使用这个脚本的人,坏人没有机会注入恶意代码。)
您可以使用envsubst
来自 gettext 工具。
您可以使用,
eval
但您可能会冒着从字符串中执行不需要的语句的风险。
至少,envsubst
只会将环境变量扩展到它们的值,就是这样,没有别的,没有命令评估,甚至没有字符串替换......
请参阅:https : //www.gnu.org/software/gettext/manual/html_node/envsubst-Invocation.html
#!/usr/bin/env bash
MYSTRING=$'Hello, ${FOO}'
FOO="world!"
REPLACED="$(
# envsubst needs variables exported to its environment.
# since this is a sub-shell, the environment scope
# is this sub-shell.
# It helps dealing with local variables that you would not want
# to export to the environment for the main shell.
# FOO's value is inherited from parent shell,
# and exported to to this sub-shell's environment.
export FOO
# pass MYSTRING as stdin here-string to envsubst
envsubst <<<"$MYSTRING"
)"
echo "${REPLACED}"
请注意,这仅适用于简单变量,不适用于数组。需要导出变量才能使用envsubst
现在如上所述,非常谨慎,这可以通过以下方式完成eval
:
#!/usr/bin/env bash
MYSTRING='Hello, ${FOO}$(echo "eval is evil" >/tmp/pawned.txt)'
FOO="world!"
eval "REPLACED=\"${MYSTRING}\""
echo "${REPLACED}"
乍一看,输出看起来合法:
Hello, world!
但是看看 cat /tmp/pawned.txt
eval is evil
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句