tags:

views:

54

answers:

2

How can I find total disk space occupied by a certain user, say located in /home/Mary? What function is available in Perl to know this?

+4  A: 

Perl has Filesys::DiskUsage for that. There is just one downside, it doesn't take the size of the directories while counting. Only the size of the files.

use Filesys::DiskUsage qw/du/;
$size = du ( { 'sector-size' => 1024 } , { 'human-readable' => 1 } , qw%/home/Mary% );
print "Total size: $size\n";
WoLpH
Quoting a path with `/` as its path separator with `qw` using `/` as the separator is somewhat unfortunate.
rafl
@rafl: Oops... my bad. My Perl is a little rusty ;)
WoLpH
Some more downsides include the fact that it doesn't handle sparse files correctly, nor can it automatically determine the block size of your filesystem. Your system's `du` command is probably more accurate.
cjm
There's really no reason to use `qw` here at all. The module's author just really likes `qw` for some reason and uses it in all the examples. Regular quotes would work just as well and be more readable.
cjm
+1  A: 

if Perl is not a must, you can use shell commands

find /home -user "Mary" -type f -printf "%s\n" | awk '{sum+=$1}END{print sum" bytes"}'
ghostdog74
@user131527: in that case, why not simply call `du` instead?
WoLpH
@WoLpH, the problem is that, in /home/Mary, there may be files not belonging to Mary (don't ask me why)... using du is less "accurate". And using find with username is more flexible
ghostdog74
@user131527: Agreed, it is slightly less acurate. But since users are normally not allowed to change the owner and creating a file automatically sets the user as an owner, the risk is negligible ;)
WoLpH
@WoLpH, sometimes, there may be files owned by root in the home directory, which either the user cannot read, or is read only user user. You will never know.
ghostdog74
Or large web server logs owned by the web server user :)
brian d foy