junkrig
junkrig

Reputation: 323

Read template file and replace variable using Bash

I am trying to read a template file then replace a variable within this file using the Bash shell as suggested in this answer.

This is my code:

#!/usr/local/bin/bash
website_name=new_website_name
while read line 
do
    eval echo "$line"
done < "/etc/apache2/extra/vhost-template.txt"

This works with a test template file (vhost-template.txt) with this content:

Directory "/Library/WebServer/Documents/${website_name}"

the placeholder is replaced and I get the correct output:

Directory "/Library/WebServer/Documents/new_website_name"

However my real template file contains some invalid characters such as the < and > characters: This is my full template file:

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "/Library/WebServer/Documents/${website_name}/web/"
    ServerName dev.${website_root_dir}.com
    ErrorLog "/private/var/log/apache2/${website_name}-dev-error_log"
    CustomLog "/private/var/log/apache2/${website_name}-dev-access_log" common

    <Directory "/Library/WebServer/Documents/${website_name}">
       Options Indexes FollowSymLinks
       AllowOverride All
       Order allow,deny
       Allow from all
    </Directory>
</VirtualHost>

and this is causing the following errors:

./virtualsetup.sh: eval: line 5: syntax error near unexpected token `newline'

./virtualsetup.sh: eval: line 5: `echo <Directory "/Library/WebServer/Documents/${website_name}">'

I have tried escaping the < and > characters using the back slash or changing them to

'&lt;' or '&gt;'

e.g.

\<Directory "/Library/WebServer/Documents/${website_name}"\>

but this gives the same error and

&lt;Directory "/Library/WebServer/Documents/${website_name}"&gt;

gives this error:

gt: command not found

I have also tried wrapping the entire template file in double quotes, but no luck.

What am I doing wrong in this case?

Thanks!

Upvotes: 0

Views: 2820

Answers (1)

cdarke
cdarke

Reputation: 44354

Place single quotes (not double) around $line:

eval echo '$line'

Edit: I misunderstood the question previously. The solution does not require an eval, but can be done using a simple substitution:

line=${line/\${website_name\}/$website_name}
echo $line

Upvotes: 1

Related Questions