Usually you run ruby code from your shell. Sometimes you want to call shell commands from Ruby, for example to find out linux system information. There are various ways to do this: the %x operator, the Kernel.system method, or backticks.

Kernel.system "command"

Kernel.system executes a command in a subshell, returning true if the command was found and ran successfully, and false otherwise. It can be used for example if you want to know how long the server has been running. Uptime is a Unix/Linux command to do this:

>> system "uptime"
15:39:41 up  5:11,  3 users,  load average: 0.13, 0.27, 0.35
=> true

Another example is to get the amount of free space on your hard disks. In this case you could use df (disk free) to display the amount of available disk space:

>> system "df -h"
Filesystem            Size  Used Avail Use% Mounted on
/dev/sda1             362G   44G  299G  13% /

Using the %x operator is similar. It returns the result of the shell command as well, for example if you want to list a directory you can type

>> directorylist = %x[find . -name '*test.rb' | sort]

Using backticks in the form `command` is identical to system(“hostname”), it returns the standard output of running cmd in a subshell. The backtick (`) is often associated with external commands in shell scripts.

>> `date`
=> "Mon Feb 22 20:10:02 CET 2010\n"

>> `uptime`
=> " 20:10:02 up  5:44,  3 users,  load average: 0.09, 0.24, 0.18\n"

>> `hostname`
=> "server42\n"