6

I have code like that:

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

All I want to get is:

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

So I did:

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

Or even more weirder things, but without any effects. I remember that someday I had similar problem and I did something like that:

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

But this solution seems to be to much complex. Have any of You heard about easier solution?

kokosing
  • 5,251
  • 5
  • 37
  • 50
  • 3
    TEXT_AFTER_FILTERED=``eval echo $TEXT_TO_FILTER`` seems to work for me – mmmmmm May 18 '10 at 07:45
  • It would work fine for me as well, but I have more complex TEXT_TO_FILTER contents (many lines, chars like < > etc.). In that way simple eval won't work – kokosing May 19 '10 at 10:39
  • Does this answer your question? [Bash expand variable in a variable](https://stackoverflow.com/questions/14049057/bash-expand-variable-in-a-variable) – LoganMzz Jan 17 '20 at 10:44

2 Answers2

4

For security reasons it's best to avoid eval. Something like this would be preferable:

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"
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
3
TEXT_AFTER_FILTERED="${TEXT_TO_FILTER//\$var/$var}"

or, using perl:

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

This is still more secure than eval.

ZyX
  • 52,536
  • 7
  • 114
  • 135