Running Shell Commands in Ruby

One of the major benefits of unix is the quantity of many simple programs that one thing great. As a developer for unix, you must learn how to leverage these commands into your own scripts. Here is how to do this in Ruby.

Say you script wants to call on the unix command to view the amount of freespace on your disks.

df -h
Filesystem        Size   Used  Avail Capacity  Mounted on
/dev/disk0s3       37G    23G    14G    62%    /
devfs             110K   110K     0B   100%    /dev
fdesc             1.0K   1.0K     0B   100%    /dev  

To add this to Ruby all you need to do is to add a line of code (note the back-ticks):

disk_free = `df -h`

That takes the output from the command and puts it into a String. So an example script that will show the “df -h” output could be

#!/usr/bin/env ruby

def disk_free
  diskfree = `df -h`
  puts diskfree


How simple is that!

Now even though it would be easier to just use the real “df” command for this, you could easily write a Ruby script to call on other scripts and use all of Ruby’s powers to modify the output. That is how I made the Server Status Sidebar, calling “uptime” and regex to get the correct string I wanted.

Happy coding.


(Found this tip by using Safari)


  1. Matthew John says:

    Thanks for this, I was looking for how to run commands.

    For those how may be interested this works on running Window commands using exatly the same syntax. Remember to use the back-ticks…

Comments are closed.