-1

I am trying to execute a shell script inside ruby code and return the result. I am using Open3 for this. Here is the code:

#!/usr/bin/env ruby

require 'rubygems'
require 'uri'
require 'net/http'

require 'open3' # require 'open3' in 1.9
AppArgs = Array.new

def get()    
  source = Net::HTTP.get('integration.twosmiles.com', '/status')
  _shellScript = "grep 'commit' status.html"
  fileHtml = File.new("status.html", "w+")
  fileHtml.puts source
  Open3.popen3(_shellScript) do |stdin, stdout, stderr|
    puts stdout
    puts stdin
    puts stderr

  end
end

get()

But it prints

#<IO:0x00000000a41ca8>
#<IO:0x00000000a41cf8>
#<IO:0x00000000a41c30>

I want to get the stings I searched in the stdout. How to achieve this?

Kirti Thorat
  • 52,578
  • 9
  • 101
  • 108
Sush
  • 1,449
  • 8
  • 26
  • 51

2 Answers2

1

If the output is very short and you want to buffer the entire output into a single string, you can simply use backticks:

`#{_shellScript}`

You can also redirect all stderr to stdout as follows

`#{_shellScript} &2>1`

Here's a quick overview of executing via backticks and other alternate methods:

Ruby, Difference between exec, system and %x() or Backticks

Community
  • 1
  • 1
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
1

If you wish to use Open3, their documentation page tells that stdout, stderr, ... are streams:

In your code, you could simply do:

puts stdout.read
puts stdin.read
puts stderr.read

Completely off topic, but ensure you have enough checks in there from an IT security point of view, you shouldn't really execute commands that are 'grepped' from the Internet.

ndrix
  • 1,191
  • 12
  • 18