Allow a bash variable contained in another variable

I have a code like this:

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 weirder things, but without any effects. I remember that one day I had a similar problem and I did something like this:

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

But this decision seems complicated. Have any of you heard of an easier solution?

+5
source share
2 answers

For security reasons, it is better 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" 
+3
source
 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 even more secure than eval.

+3
source

Source: https://habr.com/ru/post/1310082/


All Articles