Main Content

Running shell (operating system) commands from within Ruby

Archive - Originally posted on "The Horse's Mouth" - 2016-05-18 04:43:06 - Graham Ellis

Ruby is an excellent systems admin / scripting tool, allowing other shells and processes to be run from within a Ruby program in various ways.

Using backtics or the %x notation, commeand output on STDOUT is routed back into a variable - for example:
  first = `grep -c option247 ac_20160516 ac_20160517`
or
  second = %x!grep -c option247 ac_20160516 ac_20160517!
and you can embed a whole shell script this way using a here document - see [here].

The system function allows you to run a command with STDOUT routes to Ruby's STDOUT, and have the job status returned
  third = system("grep -c option247 ac_20160516 ac_20160517")
and the exec syste function transfers control to the job you're running terminating your rubys process!
  exec "df -h"

To control STDIN and STDERR as well as STDOUT, you can use shell redirects, for example
  fourth = %x!grep -c option247 ac_20160516 ac_20160517 2>&1!
and to run a shell command returning data in parallel while that command is still running, you can use a pipe, for example
  handle = IO.popen("grep -c option247 ac_20160516 ac_20160517")

For ultimate flexibility, the open3 module provides yu with control over all three standard input/outputs:
  require 'open3'
  h_in,h_out,h_err = Open3.popen3("grep -c option247 ac_20160516 ac_20160517")

though you need to be very careful of pipe buffering if you're using this.

All the examples above in complete programs (and with sample output) [here] and [here]. Examples from our Ruby course material.

Update - further example [here] to show setting of environment variables to be passed into shell commands.