7

Is there a good gem for getting recursively calculated directory sizes? In unix, I can use du, but I want a library that absorbs the difference among OS.

sawa
  • 165,429
  • 45
  • 277
  • 381

6 Answers6

5

This seems to work:

Dir.glob(File.join(dir, '**', '*'))
  .map{ |f| File.size(f) }
  .inject(:+)
yegor256
  • 102,010
  • 123
  • 446
  • 597
2

Could something like this work for you?

def directory_size(path)
  path << '/' unless path.end_with?('/')

  raise RuntimeError, "#{path} is not a directory" unless File.directory?(path)

  total_size = 0
  Dir["#{path}**/*"].each do |f|
    total_size += File.size(f) if File.file?(f) && File.size?(f)
  end
  total_size
end

puts directory_size '/etc'
lloesche
  • 198
  • 7
2

Here's my solution using http://ruby-doc.org/core-2.2.0/File.html#method-c-size:

def directory_size(path)
  size=0
  Dir.glob(File.join(path, '**', '*')) { |file| size+=File.size(file) }
  size
end
reducing activity
  • 1,985
  • 2
  • 36
  • 64
seba
  • 153
  • 8
1

Looks like sys-filesystem handles this, but you'll need to do some math to convert the available blocks into bytes (by multiplying by block-size).

coreyward
  • 77,547
  • 20
  • 137
  • 166
  • 2
    This may be due the long time passed since this answer, but the mentioned gem correctly determines the block size (and also size in bytes, cf. `bytes_{used,total,free}` only on a filesystem (=mount) level and does not seem to work to determine the size of a directory. – oliverguenther Jul 20 '15 at 14:06
-2

Check out the File::Stat class (note that it does not calculate size of directory contents, it needs to be done manually).

file = File::Stat.new('.')
puts file.size

http://ruby-doc.org/core-1.9.3/File/Stat.html#method-i-size

reducing activity
  • 1,985
  • 2
  • 36
  • 64
fullsailor
  • 886
  • 6
  • 13
  • 2
    I assume you were downvoted because this returns the size of the directory, but not the combined size of the contents of the directory. – d11wtq Feb 20 '12 at 05:55
-3

Support Tools:

diruse /M %windir%
diruse /K /S %windir%
diruse /S %windir%
diruse /, %windir%

Microsoft ... system install CD

msiexec /i %cd:~0,2%\SUPPORT\TOOLS\SUPTOOLS.MSI /q addlocal=all

Sysinternals Suite Utilities:

du.exe -l 1 %windir%

Microsoft ...

Sysinternals Suite

STTR
  • 182
  • 7