开发者

improving my backup bash script

开发者 https://www.devze.com 2023-02-06 16:05 出处:网络
Hello I keep my log files under /开发者_如何转开发opt/project/logs/ and I want to daily copy these to /opt/bkp by compressing them.

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?


You could use the logrotate(8) tool that came with your distro. :) The manpage has an example that looks close to your need:

  /var/log/news/* {
       monthly
       rotate 2
       olddir /var/log/news/old
       missingok
       postrotate
           kill -HUP `cat /var/run/inn.pid`
       endscript
       nocompress
   }

Well, not the monthly bit, or restarting inn :) 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. :)


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 :)


I'd suggest using logrotate too, but can't resist writing this script :)

proc_logs() {
  for log in /opt/project/logs/*.log; do
    cat "$log" | gzip > ${log%/*}/$(basename "$log" ".log")_`date +%Y_%m_%d`.gz;
    touch "$log";
  done
}
0

精彩评论

暂无评论...
验证码 换一张
取 消