Linux – Templating with Linux in a Shell Script

linuxshell

what I want to acomplish is:

1.) Having a config file as template, with variables like $version $path (for example apache config)

2.) Having a shell script that "fills in" the variables of the template and writes the generated file to disk.

Is this possible with a shell script. I would be very thankfull if you can name some commands/tools I can accomplish this or some good links.

Best Answer

This is very possible. A very simple way to implement this would be for the template file to actually be the script and use shell variables such as

#! /bin/bash
version="1.2.3"
path="/foo/bar/baz"
cat > /tmp/destfile <<-EOF
here is some config for version $version which should
also reference this path $path
EOF

You could even make this configurable on the command line by specifying version=$1 and path=$2, so you can run it like bash script /foo/bar/baz 1.2.3. The - before EOF causes whitespace before the lines be ignored, use plain <<EOF if you do not want that behavior.

Another way to do this would be to use the search and replace functionality of sed

#! /bin/bash
version="1.2.3"
path="/foo/bar/baz"
sed -e "s/VERSION/$version/g" -e "s/PATH/$path/" /path/to/templatefile > /tmp/destfile

which would replace each instance of the strings VERSION and PATH. If there are other reasons those strings would be in the template file you might make your search and replace be VERSION or %VERSION% or something less likely to be triggered accidentally.