How do I get the size of a directory from a Perl script? I realize that
directories' "sizes" only point to their immediate contained items, so
subdirectory sizes are not factored into "ls -l" or "ls -sk".
I was hoping to write a script that would do something like this:
# set a config variable
my $directory = 'path/to/some/dir/'
# check for flag to abort script
opendir(DIR, $somedir)
or die "Can't open $somedir";
while(readdir(DIR)) {
exit 0 if $_ eq 'stopfile';
}
closedir(DIR);
# get the total disk space "in" $directory
open DIRSIZE "ls -sk $directory |"
or die "Could not open pipe";
my $totalKbytes;
while (<DIRSIZE>) {
$totalKbytes += $1 if /^(\d+)\s+.*$/; # total up the kbytes
}
close DIRSIZE
or die "Could not close pipe, possibly did not complete";
# set the flag to abort script if 1 gig or so is being used
if ($totalKbytes > 1,000,000) { # roughly 1 gig (???)
system('touch stopfile')
or die "Could not 'touch stopfile'";
}
The problem with the above idea is that my pipe won't actually get the
total bytes recursively, only for the current $directory . Is there a
command or something that can recursively determine the amount of disk
space "contained" in a directory that I can use in this pipe?
I'm pretty new to Perl so I've probably overlooked something. (I'm also
not sure if it was legal for me to use the $1 variable before the actual
regular expression which captures $1, for that matter. Needless to say,
the above is not working code, it's more like a theoretical question.)
Thanks,
Erik