Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get available diskspace in ruby

Tags:

ruby

diskspace

What is the best way to get diskspace information with ruby. I would prefer a pure ruby solution. If not possible (even with additional gems), it could also use any command available in a standard ubuntu desktop installation to parse the information into ruby.

like image 411
Martin Flucka Avatar asked Dec 22 '10 11:12

Martin Flucka


7 Answers

You could use the sys-filesystem gem (cross platform friendly)

require 'sys/filesystem'

stat = Sys::Filesystem.stat("/")
mb_available = stat.block_size * stat.blocks_available / 1024 / 1024
like image 178
dkam Avatar answered Nov 08 '22 10:11

dkam


How about simply:

spaceMb_i = `df -m /dev/sda1`.split(/\b/)[24].to_i

where '/dev/sda1' is the path, determined by simply running df

like image 26
Steph Avatar answered Nov 08 '22 11:11

Steph


(Ruby) Daniel Berger maintains a lot of gems in this field. To be found there: sys-cpu, sys-uptime, sys-uname, sys-proctable, sys-host, sys-admin, sys-filesystem. They are (AFAIK) multi-platform.

like image 39
steenslag Avatar answered Nov 08 '22 11:11

steenslag


This is an extension to dkams answer which is not wrong, but calculated the complete space of ones drive, to check for the remaining usable .i.e. the FREE space on a drive substitute kdams secodn line with the following:

gb_available = stat.bytes_free / 1024 / 1024 / 1024

This will return the remaining free space on your drive in Gigs.

like image 26
diegeelvis_SA Avatar answered Nov 08 '22 11:11

diegeelvis_SA


Hi i have created gem for that: https://github.com/pr0d1r2/free_disk_space

You can use it by:

gem 'free_disk_space' # add line to Gemfile

Inside code use methods:

FreeDiskSpace.terabytes('/')

FreeDiskSpace.gigabytes('/')

FreeDiskSpace.megabytes('/')

FreeDiskSpace.kilobytes('/')

FreeDiskSpace.bytes('/')

like image 32
Marcin Nowicki Avatar answered Nov 08 '22 11:11

Marcin Nowicki


This works only on a Linux system: If you don't mind calling out to the shell, you can use df for a filesystem and parse the output with a Regexp:

fs_to_check = '/boot'
df_output = `df #{fs_to_check}`
disk_line = df_output.split(/\n/)[1]
disk_free_bytes = disk_line.match(/(.+)\s+(\d+)\s+(\d+)\s+(\d+)\s+/)[4].to_i
disk_free_mbs = disk_free_bytes / 1024
puts(disk_free_mbs)
like image 38
Motine Avatar answered Nov 08 '22 12:11

Motine


Similar to comment rogerdpack's comment to get the space free in GB / MB you may try following

# Get free space in Gb in present partition
gb_free = `df -BG .`.split[10].to_i

# Get free space in MB in /dev/sda1 partition
mb_free = `df -BM /dev/sda1`.split[10].to_i
puts  gb_free, mb_free
like image 44
Swapnil jaiswal Avatar answered Nov 08 '22 10:11

Swapnil jaiswal