解析另一个变量中包含的bash变量

时间:2010-05-18 07:29:21

标签: string bash replace

我有这样的代码:

TEXT_TO_FILTER='I would like to replace this $var to proper value
                in multiline text'
var=variable

我想要的只是:

TEXT_AFTER_FILTERED="I'd like to replace this variable to proper value"

所以我做了:

TEXT_AFTER_FILTERED=`eval echo $TEXT_TO_FILTER`
TEXT_AFTER_FILTERED=`eval echo $(eval echo $TEXT_TO_FILTER)`

甚至更奇怪的东西,但没有任何影响。 我记得有一天我有类似的问题而且我做了类似的事情:

cat << EOF > tmp.sh
echo $TEXT_TO_FILTER
EOF
chmod +x tmp.sh
TEXT_AFTER_FILTERED=`. tmp.sh`

但这个解决方案似乎要复杂得多。 你有没有听说过更简单的解决方案?

2 个答案:

答案 0 :(得分:3)

对于security reasons,最好避免eval。这样的事情会更好:

TEXT_TO_FILTER='I would like to replace this %s to proper value'
var=variable
printf -v TEXT_AFTER_FILTERED "$TEXT_TO_FILTER" "$var"
# or TEXT_AFTER_FILTERED=$(printf "$TEXT_TO_FILTER" "$var")
echo "$TEXT_AFTER_FILTERED"

答案 1 :(得分:3)

TEXT_AFTER_FILTERED="${TEXT_TO_FILTER//\$var/$var}"

或者,使用perl:

export var
TEXT_AFTER_FILTERED="$(echo "$TEXT_TO_FILTER" | perl -p -i -e 's/\$(\S+)/$ENV{$1} || $&/e')"

这比eval更安全。