Skip to content

Instantly share code, notes, and snippets.

@mark-rushakoff
Last active December 13, 2015 20:48
Show Gist options
  • Save mark-rushakoff/4972746 to your computer and use it in GitHub Desktop.
Save mark-rushakoff/4972746 to your computer and use it in GitHub Desktop.
How to simultaneously print and capture the output of an external command in Ruby
#!/usr/bin/env ruby
cmd = %q[echo '3...'; sleep 1;
echo '2...'; sleep 1;
echo '1...'; sleep 1;
echo 'Liftoff!']
puts '------ beginning command ------'
output_log = []
IO.popen(cmd).each do |line|
puts line
output_log << "[#{Time.now}] #{line}"
end.close # Without close, you won't be able to access $?
puts '------ done with command ------'
puts "The command's exit code was: #{$?.exitstatus}"
puts 'Here is the log:'
puts output_log.join('')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment