Redirecting $stdout and $stderr streams

Guys, how are you?
I was googling about "redirecting $stdout and $stderr" and founded

$stdout.puts "stdout"
$stderr.puts "stderr"

Then in the comand line you invoke the above snippet, lets suppose that
is called test.rb

ruby test.rb > stdout 2> stderr

What that makes is create 2 files in the current directory, one called
stdout and the other stderr, both have writed what's supposed to be in
each one. This work, but I've never seen that kind of "commands options"
or "commands arguments" and neither appears in the commons reference
ruby books, anybody knows what ">" and the rest means when invoking



Posted via

Guys, how are you?

Reasonably well, thanks

anybody knows what ">" and the rest means when invoking


This is directives to the shell, not command arguments. The order of operations is:

1. The shell looks at a command line and performs interpretation.
2. The program gets the result of that interpretation as arguments.

This is specifically IO redirection. You can test by doing something like:

ls -R > outfile.txt

Or on windows:

dir > outfile.txt

You will see that though the ls command does not know how to make an outfile.txt, one is made anyway. This is handled by the shell, and the OS itself.

That link isn't a bad intro to the same ideas



On 3 Oct 2012, at 18:53, "Damián M. González" <> wrote:

I don't know where you're headed with this, but this is what I use to
create a logfile when I'm not running from a console:


#Output log
orig_std_out = STDOUT.clone #Make a record of the default console output
to return to it later
$stdout.reopen("Rubylog.txt", "w") #Create / overwrite logfile
$stdout.sync = true #Allow interception of console output
$stderr.reopen($stdout) #Pass errorserrors to logfile

#Do stuff...
puts "I'm doing stuff!"


puts %Q|Fatal error occurred:\n#{$!}\n\nDebugging
Information:\n#{$@}|,"Error" #Logfile output


STDOUT.reopen(orig_std_out) #Restore output to console



Posted via

Thank you Jam and Joel.

Jam, well explained. The web page that you gives is very helpfull. I
suppose that 2> reference the stderr, since is a standard that the file
descriptor of stderr is 2 in every program.

Joel, I will consider your example to implement it in some way.

See you around :slight_smile:


Posted via