How do I redirect stderr and stdout to file for a Ruby script?
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.
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.
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
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With