Pregunta

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?

¿Fue útil?

Solución

If you want to add a ServerAlias line after ServerName line, why not use the 'append' command to add a line:

sed '/ServerName site.com/a\
    ServerAlias sub.site.com' tmphost >/etc/httpd/sites/site.conf

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 -i option and without the temporary file (but don't use the -i option 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:

trap "rm -f tmphost; exit 1" 0 1 2 3 13 15
...script manipulating tmphost...
rm -f tmphost
trap 0

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.

Otros consejos

I like the way with direct ServerAilas addition using sed :

sed -i "0,/^ServerName.\+/s//\0\nServerAlias sub.site.com/" /etc/httpd/sites/site.conf
apachectl reload
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top