简体   繁体   English

优化sed / tr shell脚本

[英]Optimizing a sed/tr shell script

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. 我编写了一个脚本,将ServerAlias自动添加到Apache配置文件中,然后重新启动Apache,并且对sedtr以及对shell脚本的理解都相当了解。 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. 基本上,我正在创建一个副本,用本身+新的别名替换ServerName行,使用tr插入换行符和制表符( sed对此很奇怪吗?),覆盖旧的配置文件,删除副本,然后重新启动阿帕奇

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: 如果要在ServerName行之后添加ServerAlias行,为什么不使用'append'命令添加行:

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 ). 如果您具有GNU sed,则可以使用-i选项就地进行编辑,而无需使用临时文件(但是,如果要编辑的文件具有多个硬链接,则不要使用-i选项;如果也可以是符号链接;请参见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. 当然,如果您有就地变更,则根本不需要临时文件。

I like the way with direct ServerAilas addition using sed : 我喜欢使用sed直接添加ServerAilas的方式:

sed -i "0,/^ServerName.\+/s//\0\nServerAlias sub.site.com/" /etc/httpd/sites/site.conf
apachectl reload

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM