Running a Shell Command from Ruby: Capturing the Output While Displaying the Output

Running a shell command from Ruby: capturing the output while displaying the output?

runner.rb

STDOUT.print "Enter your password: "
password = gets.chomp
puts "Here is your password: #{password}"

Note STDOUT.print

start.rb

require "stringio"

buffer = StringIO.new
$stdout = buffer

require "runner"

$stdout = STDOUT
buffer.rewind

puts buffer.read.match(/Here is your (password: .*)/).captures[0].to_s

output

Enter your password: hello
password: hello

Read more...

I recently did a write-up on this here: Output Buffering with Ruby

Ruby: execute bash command, capture output AND dump to screen at the same time

Just tee the stdout stream to stderr like so:

ruby -e 'var = `ls | tee /dev/stderr`; puts "\nFROM RUBY\n\n"; puts var' | nl

ruby -e 'var = `ls | tee /dev/stderr`; puts "\nFROM RUBY\n\n"; puts var' 2>&1 | nl

Run Shell Script from Ruby File and Capture the Output

Don't use system, it does not capture STDOUT. Use backticks (or %x()):

output = %x( #{my_script} )

Getting output of system() calls in Ruby

I'd like to expand & clarify chaos's answer a bit.

If you surround your command with backticks, then you don't need to (explicitly) call system() at all. The backticks execute the command and return the output as a string. You can then assign the value to a variable like so:

output = `ls`
p output

or

printf output # escapes newline chars


Related Topics



Leave a reply



Submit