Many answers that use eval and echo look like work, but break into different things, such as several lines trying to avoid shell metacharacters, go into a template that is not intended to extend bash, etc.
I had the same problem, and I wrote this shell function, which, as far as I can tell, handles everything correctly. It will still only suppress trailing newlines from the template due to bash command substitution rules, but I never found this to be a problem if everything else remains intact.
apply_shell_expansion() { declare file="$1" declare data=$(< "$file") declare delimiter="__apply_shell_expansion_delimiter__" declare command="cat <<$delimiter"$'\n'"$data"$'\n'"$delimiter" eval "$command" }
For example, you can use it like this: parameters.cfg , which is really a shell script that just sets the variables, and template.txt , which is a template that uses these variables:
. parameters.cfg printf "%s\n" "$(apply_shell_expansion template.txt)" > result.txt
In practice, I use this as a kind of lightweight template system.
wjl Dec 01 '13 at 20:01 2013-12-01 20:01
source share