title: Bash Templating: How to build configuration files from templates with Bash?
body: <p>I'm writing a script to automate creating configuration files for Apache and PHP for my own webserver. I don't want to use any GUIs like CPanel or ISPConfig.</p>
  <p>I have some templates of Apache and PHP configuration files. Bash script needs to read templates, make variable substitution and output parsed templates into some folder. What is the best way to do that? I can think of several ways. Which one is the best or may be there are some better ways to do that? I want to do that in pure Bash (it's easy in PHP for example)</p>
  <ol>
  <li><a href="https://stackoverflow.com/questions/415677">How to replace ${} placeholders in a text file?</a></li>
  </ol>
  <p><strong>template.txt:</strong></p>
  <pre><code>The number is ${i}
  The word is ${word}
  </code></pre>
  <p><strong>script.sh:</strong></p>
  <pre class="lang-bash prettyprint-override"><code>#!/bin/sh
  
  #set variables
  i=1
  word=&quot;dog&quot;
  #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 &quot;$line&quot;
  done &lt; &quot;./template.txt&quot;
  </code></pre>
  <p>BTW, how do I redirect output to external file here? Do I need to escape something if variables contain, say, quotes?</p>
  <ol start="2">
  <li>Using cat &amp; sed for replacing each variable with its value:</li>
  </ol>
  <p>Given template.txt (see above)</p>
  <p>Command:</p>
  <pre><code>cat template.txt | sed -e &quot;s/\${i}/1/&quot; | sed -e &quot;s/\${word}/dog/&quot;
  </code></pre>
  <p>Seems bad to me because of the need to escape many different symbols and with many variables the line will be tooooo long.</p>
  <p>Can you think of some other elegant and safe solution?</p>