Bash/Sh As A Template Engine
As part of a shell script, I wanted to generate a configuration file based on a template. At first, I thought I would use some sort of cat
and sed
combo or an awk
program. Then I realized Bash/Sh have everything needed builtin.
Considering the following template file:
Username: ${user}
And the following shell script:
#!/bin/sh
# render a template configuration file
# expand variables + preserve formatting
render_template() {
eval "echo \"$(cat $1)\""
}
user="Gregory"
render_template /path/to/template.txt > path/to/configuration_file
The call to the render_template
helper will replace ${user}
with “Gregory” in the template, keeping formatting.