Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a template.tmpl as a here-doc of a script

Tags:

bash

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
like image 800
kev Avatar asked Sep 18 '25 09:09

kev


1 Answers

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.

like image 71
mpitid Avatar answered Sep 20 '25 21:09

mpitid