I wrote a script to automatically add a ServerAlias to an Apache configuration file, then restart Apache, with a rather remedial understanding of sed and tr and probably shell scripting in general. This is what I came up with:
cp /etc/httpd/sites/site.conf tmphost &&
sed s/ServerName\ site.com/ServerName\ site.com^#ServerAlias\ sub.site.com/ \
tmphost |
tr '^#' '\n\t' >/etc/httpd/sites/site.conf &&
rm -f tmphost &&
apachectl restart
Basically I’m creating a copy, replacing the ServerName line with itself + the new alias, using tr to put in the newline and tab (sed was being weird about that?), overwriting the old configuration file, deleting the copy, then restarting Apache.
It works, but doesn’t really make mama proud, if you know what I mean. Any ideas on how to clean that up?
If you want to add a ServerAlias line after ServerName line, why not use the ‘append’ command to add a line:
There’s a ‘tab’ at the start of the extra line, which you seem to need.
If you have GNU sed, you can do the edit in-place with the
-ioption and without the temporary file (but don’t use the-ioption if the file you are editing has multiple hard links, and probably not it if it is a symlink, either; see the comments below from William Pursell).Note that you should wrap the code in:
so that the temporary file is not left around if the shell exits because of a signal. Of course, if you have an in-place alter, you don’t need the temporary file at all.