Appending text to a file using bash script

There are many ways to “skin a cat” but this worked for me. I needed a script that would append Apache web server’s configuration file, adding some url re-write parameters for projects, etc.

Problem:
- how to append parameters with illegal characters (< or >) to the end of an Apache configuration file while evaluating passed parameters as part of the path

Solution:
- add echo statements within the bash script and output to the file

Example:

#!/bin/bash

#append text to Apache httpd.conf file
echo "<library /var/svn/$1>" >> /path/to/httpd.conf
echo "DAV svn" >> /path/to/httpd.conf
echo "" >> /path/to/httpd.conf

I learned that if the script leverages variables, in this case the $1 for first argument passed, then you use double quotes instead of single quotes. This will escape the naughty characters but still evaluate the variables.

Also, I learned that by the double >> will output to the end of the file, writing each to a new line. If you have text that requires double quotes, simply encapsulate it within single quotes (provided no variables) and you should be fine.

Enjoy! Mike

7 Votes | Average: 4.57 out of 57 Votes | Average: 4.57 out of 57 Votes | Average: 4.57 out of 57 Votes | Average: 4.57 out of 57 Votes | Average: 4.57 out of 5 (7 votes, average: 4.57 out of 5)
Loading ... Loading ...


Leave a Reply

You must be logged in to post a comment.