Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 295
AOO Avatar asked Jun 10 '10 21:06

AOO


People also ask

How do I redirect both stderr and stdout to a file?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator. We have created a file named “sample.

Can you redirect stdout and stderr to the same file?

When saving the program's output to a file, it is quite common to redirect stderr to stdout so that you can have everything in a single file. > file redirect the stdout to file , and 2>&1 redirect the stderr to the current location of stdout . The order of redirection is important.


2 Answers

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 
like image 128
Mark Rushakoff Avatar answered Nov 26 '22 01:11

Mark Rushakoff


Note: reopening of the standard streams to /dev/null is a good old method of helping a process to become a daemon. For example:

# daemon.rb $stdout.reopen("/dev/null", "w") $stderr.reopen("/dev/null", "w") 
like image 29
argent_smith Avatar answered Nov 26 '22 01:11

argent_smith