No tools necessary other than /bin/sh
. Given a template file of the form
Version: ${version}
Path: ${path}
or even with mixed shell code included
Version: ${version}
Path: ${path}
Cost: ${cost}\$
$(i=1; for w in one two three four; do echo Param${i}: ${w}; i=$(expr $i + 1); done)
and a shell parsable configuration file like
version="1.2.3-r42"
path="/some/place/under/the/rainbow/where/files/dance/in/happiness"
cost="42"
it is a simple matter to expand this to
Version: 1.2.3-r42
Path: /some/place/under/the/rainbow/where/files/dance/in/happiness
Cost: 42$
Param1: one
Param2: two
Param3: three
Param4: four
Indeed, given the path to the configuration file in shell variable config_file
and the path to the template file in template_file
, all you need to do is:
. ${config_file}
template="$(cat ${template_file})"
eval "echo \"${template}\""
This is perhaps prettier than having complete shell script as the template file (@mtinberg's solution).
The complete naive template expander program:
#!/bin/sh
PROG=$(basename $0)
usage()
{
echo "${PROG} <template-file> [ <config-file> ]"
}
expand()
{
local template="$(cat $1)"
eval "echo \"${template}\""
}
case $# in
1) expand "$1";;
2) . "$2"; expand "$1";;
*) usage; exit 0;;
esac
This will output the expansion to standard output; just redirect standard output to a file or modify the above in obvious fashion to produce the desired output file.
Caveats: Template file expansion would not work if the file contained unescaped double quotes ("
). For security reasons, we should probably include some obvious sanity checks or, even better, perform shell escaping transformation if the template file is generated by external entity.