Hi,

I've been trying to redirect the output of commands invoked by
"system", by changing the $stdout variable in Ruby.

I want to avoid using shell redirections in my commands:

    system "echo 1 2 3 > log-file"    # I want to avoid this

So instead I wrote code like this:

    #----------------------------------------
    system "echo In the beginning, to STDOUT I hope."

    $saved_stdout = $stdout
    $stdout = File.open("log-file", "w")

    system "echo After redirect, to log-file I hope."

    $stdout = $saved_stdout

    system "echo Original restored, to STDOUT I hope."
    #----------------------------------------

When I execute this code I get:

    $ ruby test-system.rb
    In the beginning, to STDOUT I hope.
    $
    $ cat log-file
    After redirect, to log-file I hope.
    Original restored, to STDOUT I hope.
    $

So obviously, the "system" calls are affected by my change of $stdout
but only in *one* direction. I can't figure out why I get the current
behaviour. Why is the last system output also written to the
log file ?

I'm reasonably new to Ruby, but have used Perl for many years, so maybe
my expectations are influenced by how this can be done in Perl:

    #----------------------------------------
    system "echo In the beginning, to STDOUT I hope.";

    open(SAVED_STDOUT, ">&STDOUT") || die;
    open(STDOUT, "> log-file") || die;

    system "echo After redirect, to log-file I hope.";

    open(STDOUT, ">&SAVED_STDOUT") || die;

    system "echo Original restored, to STDOUT I hope.";
    #----------------------------------------

What is the best way to accomplish the same as above in Ruby ?
And what is the explanation of the current Ruby-behaviour ?

Thanks,

/Johan Holmberg