User Tools

Site Tools


Perl disk usage subroutine

“Yet another unix du” =)
I wrote this for specific mailbox size calculation.

du.pl
#!/usr/bin/env perl
 
use strict;
use warnings;
 
use File::stat;
 
sub du {
    my ($subj, $maxdeep, $deep) = @_;
    $maxdeep ||= 10;
    $deep ||= 0;
    my $stat = stat($subj);
    return int($stat->size/1024) if -f $subj;
 
    $deep += 1;
    return 0 if $deep > $maxdeep;
    opendir(my $dir, $subj) or return 0;
    my $res ||= 0;
    foreach my $rec (readdir $dir) {
        next if $rec =~ /^.$/;
        next if $rec =~ /^..$/;
        $res = $res + du("$subj/$rec", $maxdeep, $deep);
    }
    $res;
}
 
my $subj = $ARGV[0] || ".";
print du($subj), "\n";
 
#EOF

Out

# ./du.pl /var/log
543549

First PagePrevious PageBack to overviewNext PageLast Page