Alex Rivera | Logout

Getting output of system() calls in Ruby

Asked 2009-03-27T15:12:54.343
361

If I call a command using Kernel#system in Ruby, how do I get its output?

system("ls")
Edit
Report

3 Answers

28

If you need to escape the arguments, in Ruby 1.9 IO.popen also accepts an array:

p IO.popen(["echo", "it's escaped"]).read

In earlier versions you can use Open3.popen3:

require "open3"

Open3.popen3("echo", "it's escaped") { |i, o| p o.read }

If you also need to pass stdin, this should work in both 1.9 and 1.8:

out = IO.popen("xxd -p", "r+") { |io|
    io.print "xyz"
    io.close_write
    io.read.chomp
}
p out # "78797a"
answered 2012-07-04T10:36:15.203
21

You use backticks:

`ls`
answered 2009-03-27T15:17:37.750
11

If you want the output redirected to a file using Kernel#system, you can do modify descriptors like this:

redirect stdout and stderr to a file(/tmp/log) in append mode:

system('ls -al', :out => ['/tmp/log', 'a'], :err => ['/tmp/log', 'a'])

For a long running command, this will store the output in real time. You can also, store the output using a IO.pipe and redirect it from Kernel#system.

answered 2013-05-26T04:58:41.497

Your Answer