Tuesday, January 26, 2010

Rotating log files without parsing ls

When people are rotating custom log files, they often parse ls because, well, because they don't know any better.

Now you will and you can smack them appropriately.

If you have a bunch of log files with sequential file names (like dates), then you can easily trim to a specific number of files to keep.
$ echo mylog.*.gz
mylog.20100126.gz
mylog.20100125.gz
mylog.20100124.gz
mylog.20100123.gz
mylog.20100122.gz
mylog.20100121.gz
mylog.20100120.gz
mylog.20100119.gz
$ numsave=5
$ echo mylog.*.gz | tr " " "\012" | sort -nr | while read f
> do
> if [ ${numsave} -gt "0" ] ; then
> numsave=$((numsave - 1))
> else
> echo DELETE $f
> fi
> done
DELETE mylog.20100121.gz
DELETE mylog.20100120.gz
DELETE mylog.20100119.gz
And you can easily substitute an "rm" where I put "echo DELETE".

But what if you named the files like a moron such that you can't sort by name. Like, "26Jan2010", that kind of moron.
$ echo mylog.*.gz
mylog.26Jan2010.gz

mylog.25Jan2010.gz

mylog.24Jan2010.gz

mylog.23Jan2010.gz

mylog.22Jan2010.gz

mylog.21Jan2010.gz

mylog.20Jan2010.gz

mylog.19Jan2010.gz

$ numsave=5
$ ls -t1 mylog.*.gz | while read f
> do
> if [ ${numsave} -gt "0" ] ; then
> numsave=$((numsave - 1))
> else
> echo DELETE $f
> fi
> done
DELETE mylog.21Jan2010.gz
DELETE mylog.20Jan2010.gz
DELETE mylog.19Jan2010.gz

Labels: , , ,

0 Comments:

Post a Comment

<< Home