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.
Asked
Active
Viewed 6,608 times
7

sawa
- 165,429
- 45
- 277
- 381
-
Related: http://stackoverflow.com/questions/3632074/what-is-the-fastest-way-to-calculate-disk-usage-per-customer – coreyward Feb 20 '12 at 00:03
-
1Related: http://stackoverflow.com/questions/4508692/get-available-diskspace-in-ruby – coreyward Feb 20 '12 at 00:06
6 Answers
5
This seems to work:
Dir.glob(File.join(dir, '**', '*'))
.map{ |f| File.size(f) }
.inject(:+)

yegor256
- 102,010
- 123
- 446
- 597
-
I think you're actually just getting the length of the string with `(&:size)` there. What you want instead is `{ |file| File.size(file) }`. – Ryan Lue Jun 24 '17 at 08:25
-
1
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
-
2This 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

reducing activity
- 1,985
- 2
- 36
- 64

fullsailor
- 886
- 6
- 13
-
2I 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 ...

STTR
- 182
- 7
-
It's not clear how this solves the issue. YOu'll need to explain – New Alexandria Mar 03 '16 at 23:12