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

I am trying to automate the creation of a site for our internal development server.

Currently it consists of creating a system user, mysql user, database and apache configuration. I know how I can do everything in one bash file, but I wanted to ask if there is a way to generate apache configuration cleaner.

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

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

Any help is appreciated.

+6
source share
3 answers

Select a method for marking parameters. One of the possibilities is :parameter: but any similar pair of markers that will not be confused with legal text for the template file 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 situation where you sometimes need to edit something, and sometimes not, it might be easier for you to create the appropriate sed commands in a batch file, and then run this:

 { 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 that the temporary does not revive 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 deleted when the script exits for most likely signals. You can save non-zero exit status from previous commands and use exit $exit_status after trap 0 command.

+7
source

I am surprised that no one mentioned the documents here. This is probably not what the OP wants, but, of course, a way to improve the readability of the script you started with. Just make sure to avoid or parameterize any constructions that the shell will perform by substitutions.

 #!/bin/sh # For example sake, a weird value # This is in single quotes, to prevent substitution literal='$%"?*=`!!' user=me cat <<HERE >httpd.conf # Not a valid httpd.conf User=${user} Uninterpolated=${literal} Escaped=\$dollar HERE 

In this context, I would recommend $ {variable} over the equivalent variable $ for clarity and avoid any possible ambiguity.

+4
source

Use sed, for example

 sed s/%foo%/$foo/g template.conf > $newdir/httpd.conf 
+1
source

Source: https://habr.com/ru/post/905858/


All Articles