3

I am running the following (backup) code in a Ruby script:

 for directory in directories
   print `s3sync.rb --exclude="#{EXCLUDE_REGEXP}" --delete --progress -r #{directory} my.amazon.backup.bucket:#{directory}`
 end

I would like the output of the executed subprocess to be echoed to the terminal in real time (as opposed to having to wait until the subprocess returns). How do I do that?

Ron Gejman
  • 6,135
  • 3
  • 25
  • 34

3 Answers3

4

IO.popen creates a process and returns an IO object for stdin and stdout of this process.

IO.popen("s3sync.rb …").each do |line|
  print line
end
johannes
  • 7,262
  • 5
  • 38
  • 57
2

If you don't need for your code to see stdout, and it's sufficient that a human sees it, than system is fine. If you need your code to see it, there are numerous solutions, popen being the simplest, giving your code access to stdout, and Open3 giving your code access to both stdout and stderr. See: Ruby Process Management

josliber
  • 43,891
  • 12
  • 98
  • 133
Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
0

Oops, figured it out right away. I had to use exec() instead of ``

This does what I want:

 for directory in directories
      exec `s3sync.rb --exclude="#{EXCLUDE_REGEXP}" --delete --progress -r #{directory} my.amazon.backup.bucket:#{directory}`
 end
Ron Gejman
  • 6,135
  • 3
  • 25
  • 34
  • 1
    Are you sure this does what you want? The documentation states that exec *replaces* the current process, so your program will end execution after s3sync.rb is run for the first directory. I think you'll want to use Kernel#system instead. More info at http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html – DataWraith Dec 29 '09 at 13:29
  • Oh, good call. I only have 1 directory that's being backed up thus far so I missed this! – Ron Gejman Dec 29 '09 at 19:19