Finding free disk space in Ruby
UPDATED I can’t find a standard Ruby idiom for finding out the free/occupied disk space on a partition, so here’s a hack for doing it under Linux:
1 2 3 4 5 6 7 8 9 | def disk_used_space( path ) `df -Pk #{path} |grep ^/ | awk '{print $3;}'`. to_i * 1.kilobyte end def disk_free_space( path ) `df -Pk #{path} |grep ^/ | awk '{print $4;}'`. to_i * 1.kilobyte end |
The -P (POSIX compliant output) argument to df is important, it forces the output to be more regular, thus easier to parse. Without -P, you’ll run into trouble if the names of the disk devices are particularly long, e.g. if the machine uses LVM:
mymachine:~# df
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/md0 9614052 2819896 6305788 31% /
/dev/mapper/storage-s1
331624912 395808 314383488 1% /mnt/s1
/dev/mapper/storage-s2
109681544 192248 103917712 1% /mnt/s2
The 1.kilobyte idiom is available only if you use ActiveSupport, e.g. in a Rails application. If you can’t use ActiveSupport, just write 1024 instead.
Update: the -P option is not enough, you should also use -k to get the output in 1 KB blocks. Thanks to commenter Martin Rehfeld for the tip.
Hope you find this useful.
Categories: linux, programming
Other version without so many os commands usage:
def disk_space(path, used)
path_info = `df -P #{path}`.split(“\n”)[1]
if(used)
path_info.split(” “)[2].to_i
else
path_info.split(” “)[3].to_i
end
end
p disk_space(“/”, true) – returns the used space for “/” mount point (bytes)
p disk_space(“/”, false) – returns the available space for “/” mount point (bytes)
“Parse” is a fascinating word. I truly believe that. Thanks to mr. Dogariu for reminding it to me.
Please bear in mind that not every filesystem uses 1k blocks. To make sure you always get sizes calculated with 1k blocks, use df -Pk
Thanks, Martin! I updated the post to incorporate your tip.