Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return output from "system" command in Ruby?

Tags:

ruby

I have to execute a shell command from Ruby script but I have to retrieve the output so that I can use it in the script later on.

Here is my code:

output = system "heroku create" # => true

But the system command returns a boolean and not the output.

Simply said, system "heroku create" has to output to my screen (which it does) but also return the output so I can process it.

like image 736
never_had_a_name Avatar asked Aug 28 '10 08:08

never_had_a_name


2 Answers

You could use

output = `heroku create`

See: http://ruby-doc.org/core/classes/Kernel.html

like image 184
NullUserException Avatar answered Sep 29 '22 10:09

NullUserException


The Open3 library gives you full access to the standard IO streams (STDIN, STDOUT and STDERR). It's part of Ruby, so there's no need to install a gem:

require 'open3'

stdin, stdout, stderr = Open3.popen3("heroku create")
puts stdout.read
stdin.close; stdout.close; stderr.close

or you can use the block form which closes the streams implicitely:

require 'open3'

Open3.popen3("heroku create") do |stdin, stdout, stderr|
    puts stdout.read
end

See the Open3 documentation for the full details.

Edit: Added extra stream closing details. Thanks Christopher and Gregory.

like image 43
Bernard Avatar answered Sep 29 '22 11:09

Bernard