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
Is it possible to capture output from a system command and redirect it?
Using abort
and an exit message, will pass the message to STDERR (and the script will fail with exit code 1). You can pass this shell command output in this way.
This is possibly not the only (or best) way, but it has worked for me in the past.
[edit]
You can also redirect the output to a file (using standard methods), and read that file outside the ruby 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
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} )
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
Log all output from a shell command
You can use IO::popen for this:
IO.popen("apt-get install foobar") do |apt|
apt.each do |line|
puts line
end
end
Hope this helps
Related Topics
How to Get Filename Without Extension from File Path in Ruby
How to Run Rake Tasks Within a Ruby Script
What Is a Regex to Match a String Not At the End of a Line
Ruby: Problem Installing Eventmachine Under Windows 7
Ruby: What Does the Comment "Frozen_String_Literal: True" Do
Putting French (Accented) Characters in Ruby File
Undefined Symbol: Sslv2_Method When Running Bundle Install
Gem Install Fails with Openssl Failure
Cron Job Not Working in Whenever Gem
How to Access Method Arguments in Ruby
How to Display Ruby on Rails Form Validation Error Messages One At a Time
Extract a Substring from a String in Ruby Using a Regular Expression
Getting "Warning! Path Is Not Properly Set Up" When Doing Rvm Use 2.0.0 --Default