This post originated from an RSS feed registered with Ruby Buzz
by James Britt.
Original Post: Fun with Ruby and KDE
Feed Title: James Britt: Ruby Development
Feed URL: http://feeds.feedburner.com/JamesBritt-Home
Feed Description: James Britt: Playing with better toys
Every so often I find a need for some small script that will reduce or eliminate some annoyance.
One case is running out of disk space. I really could not tell you what in the world is consuming my laptop drive, but 200G is evidently not enough.
Every so often I think to check the amount of free space, and move off or delete this or that. But sometimes I suddenly find myself with zero free space, and some applications just don’t handle this well.
I decided to create a cron task that would check the disk usage and warn me when free space fell below some set amount.
The Ruby code was simple (though potentially hackish. If there’s a better way to get the amount of free disk I’d like to hear of it).
Here’s grabbing the disk space
def free_diskspace drive
results = `df -h #{drive}`
# Filesystem Size Used Avail Use% Mounted on
data = results.split( "\n").last.split(' ')
value = data[3]
value.sub!( /G$/, '')
value
end
To issue an alert when space is low, I used KDE’s built-in kdialog command. There’s a Ruby lib that wraps this, but invoking it directly is simple enough.
def alert msg
puts `kdialog --display :0 --error "#{msg}"`
end
The logic is basic:
space = free_diskspace '/dev/sda1'
alert "Running low on disk space: #{space}" if space.to_f < 2.0
One point that wasn’t obvious when I wrote this: the cron task may not be using the same X display as the user, so the message box may not be seen. The fix is the explicit use of --display :0 when calling kdialog.