Archive

Archive for December, 2008

Finding free disk space in Ruby

December 16th, 2008 6 comments

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