I am writing a script to automate the creation of configuration files for Apache and PHP for my own web server. I do not want to use graphical interfaces like CPanel or ISPConfig.
I have several Apache and PHP configuration file templates. Bash script is necessary to read the templates, make a change of variables and display the analyzed patterns in a folder. What is the best way to do this? I can think of several ways. Which one is the best, or maybe there are some ways to do this? I want to do it in pure Bash (for example, it's just in PHP)
1) How to replace $ {} placeholders in a text file?
template.txt:
the number is ${i} the word is ${word}
script.sh:
#!/bin/sh #set variables i=1 word="dog" #read in template one line at the time, and replace variables #(more natural (and efficient) way, thanks to Jonathan Leffler) while read line do eval echo "$line" done < "./template.txt"
By the way, how do I redirect the output to an external file here? Do I need to avoid something if the variables contain, say, quotation marks?
2) Using cat and sed to replace each variable with its value:
This file template.txt:
the number is ${i} the word is ${word}
Team:
cat template.txt | sed -e "s/\${i}/1/" | sed -e "s/\${word}/dog/"
It seems bad to me to avoid many different characters and with many variables, the line length will be longer.
Can you think of another elegant and safe solution?
bash templates templating
Vladislav Rastrusny May 26 '10 at 15:12 2010-05-26 15:12
source share