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

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

+37
redirect ruby stdout stderr
Jun 10 '10 at 21:17
source share
4 answers

Inside the Ruby script, you can redirect stdout and stderr using the IO#reopen .

 # 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
+55
Jun 10 '10 at 21:38
source share

Note: reopening standard threads in / dev / null is a good old method to help a process become a daemon. For example:

 # daemon.rb $stdout.reopen("/dev/null", "w") $stderr.reopen("/dev/null", "w") 
+13
Apr 13 '11 at 17:26
source share
 def silence_stdout $stdout = File.new( '/dev/null', 'w' ) yield ensure $stdout = STDOUT end 
+7
May 29 '12 at 23:51
source share
 ./yourscript.rb 2>&1 > log.txt 

redirects stdout and stderr to the same file.

+5
Jun 10 '10 at 21:19
source share



All Articles