Hellnar
Hellnar

Reputation: 64793

improving my backup bash script

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?

Upvotes: 0

Views: 1035

Answers (3)

Maxim Sloyko
Maxim Sloyko

Reputation: 15866

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
}

Upvotes: 0

Spacedman
Spacedman

Reputation: 94182

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

Upvotes: 0

sarnold
sarnold

Reputation: 104050

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

Upvotes: 2

Related Questions