3

In Ruby I'm using backticks to execute (many) shell commands. How do I get the shell command output displayed on the console?

A bit more detail. If I run an (ansible) command like the following, I get lots of scrolling output on the console:

% ansible-playbook config.yml -e foo=bar -e baz=qux

PLAY [base setup] **************************************************************

TASK [setup] *******************************************************************
ok: [10.99.66.210]

... etc, etc

However if I execute the same command from Ruby (using backticks) I don't see any output on the console:

# cmd = ansible-playbook config.yml -e foo=bar -e baz=qux
`#{cmd}`

Which is unfortunate, as I'd like to see the output in order to debug. I could redirect the output from the Ruby script to a (tailed) log file, however I want to see the output as it happens.

Sonia Hamilton
  • 4,229
  • 5
  • 35
  • 50
  • 1
    I don't think you need to interpolate `cmd` with `#{}` – marcosbeirigo Mar 17 '16 at 09:52
  • 1
    You need to `puts \`#{cmd}\``, but I'm not sure if it will show anything until it completes. Otherwise use [popen3](http://ruby-doc.org/stdlib-2.0.0/libdoc/open3/rdoc/Open3.html#method-c-popen3) – David K-J Mar 17 '16 at 09:55

1 Answers1

1

Thanks to David K-J's comment, as well as Ruby—Open3.popen3

The solution for me was Open3#popen2e, for example:

# cmd = ansible-playbook config.yml -e foo=bar -e baz=qux
puts cmd
if execute then
  puts "Executing..."
  Dir.chdir("..") do
    Open3.popen2e(cmd) do |i,oe,t|
      oe.each { |line| puts line }
    end
  end
end
Community
  • 1
  • 1
Sonia Hamilton
  • 4,229
  • 5
  • 35
  • 50