改进我的备份 bash 脚本
你好 我将日志文件保存在 /opt/project/logs/ 下,并且我想每天通过压缩将它们复制到 /opt/bkp。
为此,我写了这个并且运行良好:
#!/bin/bash
getdate(){
date --date="$1 days ago" "+%Y_%m_%d"
}
rm -rf "/opt/bkp/logs/myapp_log_"$(getdate 365).gz ;
/bin/cat /opt/project/logs/myapp.log | gzip > /opt/bkp/logs/myapp_log_`date +%Y_%m_%d`.gz ;
echo "" > /opt/project/logs/myapp.log ;
但是它不是功能性的或通用的,我将有几个应用程序用它们的名称保存文件,即在同一个 /opt 下的
文件夹。如何将其作为一个“函数”,其中脚本读取 app1.log app2.log
/project/logs//opt/project/logs/
目录下的每个文件并备份以 .log
扩展名结尾的每个文件?
Hello
I keep my log files under /opt/project/logs/ and I want to daily copy these to /opt/bkp by compressing them.
For this I have written this and works well:
#!/bin/bash
getdate(){
date --date="$1 days ago" "+%Y_%m_%d"
}
rm -rf "/opt/bkp/logs/myapp_log_"$(getdate 365).gz ;
/bin/cat /opt/project/logs/myapp.log | gzip > /opt/bkp/logs/myapp_log_`date +%Y_%m_%d`.gz ;
echo "" > /opt/project/logs/myapp.log ;
However it is not functional or general, I will have several applications saving files with their names ie app1.log app2.log
under the same /opt/project/logs/
folder. How can I make this as a "function" where script reads each file under /opt/project/logs/
directory and taking backup of each file ends with .log
extension?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用发行版附带的
logrotate(8)
工具。 :) 联机帮助页有一个看起来接近您需要的示例:好吧,不是
monthly
位,或重新启动inn
:) 但我希望您明白您可以轻松地将新的配置文件添加到/etc/logrotate.d/
中,而不必再担心它。 :)You could use the
logrotate(8)
tool that came with your distro. :) The manpage has an example that looks close to your need:Well, not the
monthly
bit, or restartinginn
:) but I hope you get the idea that you could easily add a new config file to/etc/logrotate.d/
and not worry about it again. :)您是否考虑过使用“logrotate”?它会为你压缩和修剪日志,可选择踢出需要踢出的进程来关闭日志文件、泡茶等等。这可能是你的 Linux 机器用来进行日志管理的。
man logrotate
了解更多。按照您的方式,当您获得所需的功能时,您将已经编写了 logrotate :)
Have you considered using 'logrotate'? It will compress and prune logs for you, optionally kick processes that need kicking to close log files, make tea, etc etc. It's probably what your linux box uses for log management.
man logrotate
for more. The way you are going, you will have written logrotate by the time you get the functionality you want :)
我也建议使用
logrotate
,但无法抗拒编写此脚本:)I'd suggest using
logrotate
too, but can't resist writing this script :)