I have a template file(template.tmpl
):
Hello, $x
Hello, $y
I have a script file(variables.sh
):
#!/bin/bash
x=foo
y=bar
# I want to include template.tmpl as a here-doc
How to include template.tmpl
as a here-doc
of variables.sh
.
So that, the rendered output should be:
Hello, foo
Hello, bar
Edit: (in 2012)
I think replace
is a good command for my job:
$ cat template.tmpl | replace '$x' foo '$y' bar
A more sophisticated tool:
$ cheetah compile template.tmpl
$ x=foo y=bar python template.py --env
Edit: (in 2024)
Maybe envsubst is the tool I should try:
set -o allexport
source variables.sh
set +o allexport
envsubst < template.tmpl
I use this function in one of my projects. It builds an actual here document from the template and then executes it in the current shell using .
:
# usage: apply_template /path/to/template.txt
apply_template () {
(
trap 'rm -f $tempfile' EXIT
tempfile=$(mktemp $(pwd)/templateXXXXXX)
echo 'cat <<END_TEMPLATE' > $tempfile
cat $1 >> $tempfile
echo END_TEMPLATE >> $tempfile
. $tempfile
)
}