用字符串做Shell替换

时间:2019-09-13 21:05:13

标签: bash shell

我在内存中有一个字符串,分配给bash变量,其中包含占位符。我想替换那些在环境中使用变量的对象。

例如

#!/bin/bash
MYSTRING='Hello, ${FOO}'
export FOO="world!"
REPLACED=$(how?${MYSTRING})
echo "${REPLACED}"
# should return Hello, world!

我需要的是$(how?${MYSTRING})这部分

(我是唯一将使用此脚本的人,并且不良行为者没有机会注入恶意代码。)

1 个答案:

答案 0 :(得分:1)

您可以在gettext工具中使用envsubst

  

您可以使用eval,但是您有有可能从字符串中执行不需要的语句

至少,envsubst只会将环境变量扩展为它们的值,仅此而已,仅此而已,没有命令求值,甚至没有字符串替换...

请参阅:https://my-app.herokuapp.com

#!/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