Konstantin
Konstantin

Reputation: 3123

How to redirect STDOUT and STDERR in Ruby and make them equal?

When I call a command in Ruby with %x{command}, standard output is captured, and standard error shows on the screen. However I would like both to be captured and I want to watch both on the screen too. How can I achieve this?

%x{command 2>&1 1>&2}

construction seems to be not working.

Upvotes: 0

Views: 593

Answers (2)

Victor Moroz
Victor Moroz

Reputation: 9225

2.1.3 :005 > %x{(ls -d /boot 2>&1) | tee /dev/stderr}
/boot
 => "/boot\n" 

2.1.3 :006 > %x{(ls /no_such_file 2>&1) | tee /dev/stderr}
ls: cannot access /no_such_file: No such file or directory
 => "ls: cannot access /no_such_file: No such file or directory\n" 

Upvotes: 0

ptierno
ptierno

Reputation: 10074

Your redirection is all wrong.

2>&1 Here you are redirecting stderr to stdout

1>&2 Here you are redirecting stdout back to stderr

This is what you want:

%x{command 2>&1}

Be sure to call puts to get the output to the screen from a script. (since everything is going to stdout now instead of stderr)

puts %x{command 2>&1}

Hope this helps.

Upvotes: 1

Related Questions