in reply to Deleting Oldest Logfiles

First I'd use df to get the used space of a partition (du recursively walks the directory structure, which is rather expensive).
use strict; use warnings; sub partition_usage { my $partition = shift; my $line = (`/bin/df -B 1024 $partition`)[-1]; return 1024 * (split(/\s+/, $line))[2]; } # test it: print partition_usage('/home/'), "\n";

Then you should get a list of the log files you might want to delete. Then sort them by modification time. This example assumes that they are all in the current directory:

my @files = glob 'logfile_*.log.gz'; @files = reverse sort { -M $a <=> -M $b } @files.

The the documentation of -M and sort for more details.

Then it's just a matter of walking through these files, and delete until you no longer exceed your size limit:

my $limit = 10 * 1024**3; # 10 GB for my $filename (@files) { last if partition_usage('/var/log/') < $limit; unlink $filename or warn "Can't delete file '$filename': $!"; }

Replies are listed 'Best First'.
Re^2: Deleting Oldest Logfiles
by longjohnsilver (Acolyte) on Oct 23, 2008 at 11:44 UTC
    Hi Monks,

    Firstly thanks a lot for all your help, and shame on me for that error on the first chomp snippet. Moritz thanks to you especially cause the code you sent seems very elegant and functional to solve my problem. I decided to put it in my script, anyway since i'm trying to learn Perl... There are 2 obscure points in your code which i still didn't grasp completely and i'd be glad if you or somebody else in this monastery could explain them to me.

    1. The -1 and the 2 within square brackets inside the partition_usage sub. What is their exact purpose?
    2. If i had to glob for zipped logfiles within subdirectories how could i do it?

    Thx Again,

    Francesco
      1. The -1 and the 2 within square brackets inside the partition_usage sub. What is their exact purpose?

      The construct before these square brackets return lists. [2] picks the third item of that list (remember, indexes are zero-based) (here: the third whitespace delimited field of the input), and [-1] returns the last list item.

      2. If i had to glob for zipped logfiles within subdirectories how could i do it?

      If you have fixed depth, say 2, you could write */*/*.log.gz. If not you'd have to use File::Find (or File::Find::Rule, which beginners seem to like better).

        Hi Moritz,
        Since i got fixed depth i adopted the asterisk solution, tested the code and everythings seems to work fine!! Thx again!

        F