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
The following bash function evaluates arbitrary files as here documents, allowing bash to be used as a mini-template language. It does not require any temporary files.
#!/bin/bash
template() {
file=$1
shift
eval "`printf 'local %s\n' $@`
cat <<EOF
`cat $file`
EOF"
}
Variables will be expanded from the environment or can be passed directly, e.g. for the template file
Hello $x, $y, $z
and snippet
y=42
for i in 1 2; do
template template.txt x=$i z=end
done
the output will be
Hello 1, 42, end
Hello 2, 42, end
Note that arbitrary code in the template file will be executed as well, so make sure you trust whoever wrote it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With