How do I redirect stderr and stdout to file for a Ruby script?

AOO picture AOO · Jun 10, 2010 · Viewed 33.1k times · Source

How do I redirect stderr and stdout to file for a Ruby script?

Answer

Mark Rushakoff picture Mark Rushakoff · Jun 10, 2010

From within a Ruby script, you can redirect stdout and stderr with the IO#reopen method.

# a.rb
$stdout.reopen("out.txt", "w")
$stderr.reopen("err.txt", "w")

puts 'normal output'
warn 'something to stderr'
$ ls
a.rb
$ ruby a.rb
$ ls
a.rb    err.txt out.txt
$ cat err.txt 
something to stderr
$ cat out.txt 
normal output