Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I script file generation from a template using bash?

Tags:

bash

printf

sed

awk

I am trying to automate the set up of site creation for our in-house development server.

Currently, this consists of creating a system user, mysql user, database, and apache config. I know how I can do everything in a single bash file, but I wanted to ask if there was a way to more cleanly generate the apache config.

Essentially what I want to do is generate a conf file based on a template, similar to using printf. I could certainly use printf, but I thought there might be a cleaner way, using sed or awk.

The reason I don't just want to use printf is because the apache config is about 20 lines long, and will take up most of the bash script, as well as make it harder to read.

Any help is appreciated.

like image 637
Brendan Avatar asked Jan 12 '12 19:01

Brendan


People also ask

What command can use to create a file using Bash?

To create a new file, run the "cat" command and then use the redirection operator ">" followed by the name of the file. Now you will be prompted to insert data into this newly created file. Type a line and then press "Ctrl+D" to save the file.


1 Answers

Choose a way of marking parameters. One possibility is :parameter:, but any similar pair of markers that won't be confused with legitimate text for the template file(s) is good.

Write a sed script (in sed, awk, perl, ...) similar to the following:

sed -e "s/:param1:/$param1/g" \
    -e "s/:param2:/$param2/g" \
    -e "s/:param3:/$param3/g" \
    httpd.conf.template > $HTTPDHOME/etc/httpd.conf

If you get to a point where you need sometimes to edit something and sometimes don't, you may find it easier to create the relevant sed commands in a command file and then execute that:

{
echo "s/:param1:/$param1/g"
echo "s/:param2:/$param2/g"
echo "s/:param3:/$param3/g"
if [ "$somevariable" = "somevalue" ]
then echo "s/normaldefault/somethingspecial/g"
fi
} >/tmp/sed.$$
sed -f /tmp/sed.$$ httpd.conf.template > $HTTPDHOME/etc/httpd.conf

Note that you should use a trap to ensure the temporary doesn't outlive its usefulness:

tmp=/tmp/sed.$$   # Consider using more secure alternative schemes
trap "rm -f $tmp; exit 1" 0 1 2 3 13 15  # aka EXIT HUP INT QUIT PIPE TERM
...code above...
rm -f $tmp
trap 0

This ensures that your temporary file is removed when the script exits for most plausible signals. You can preserve a non-zero exit status from previous commands and use exit $exit_status after the trap 0 command.

like image 63
Jonathan Leffler Avatar answered Sep 21 '22 13:09

Jonathan Leffler