Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bat redirecting stderr to stdout has weird behaviour

I have a bat script which at one point redirects the stderr of a process to the stdout, and then writes it to a file. I used to do it like this:

process.exe 2>&1 > file.txt

However, this doesn't redirect the stderr to the file ( for reasons I can't understand ). When I modified the line to :

process.exe > file.txt 2>&1 

The whole thing worked. Aren't these two equivalent?

like image 948
Geo Avatar asked Feb 04 '10 08:02

Geo


3 Answers

The first example essentially does:

stderr = stdout;
stdout = "file.txt";

So, stderr is still pointing at the original stdout. Your second example does:

stdout = "file.txt";
stderr = stdout;

So, both stderr and stdout now reference file.txt. It's annoyingly subtle.

like image 144
developmentalinsanity Avatar answered Sep 28 '22 16:09

developmentalinsanity


The redirection 2>&1 works at the end of the command line. It will not work as the first redirection parameter, the redirection requires a filename and the 2>&1 at the end. You're effectively trying to redirect stderr but there is no placeholder to store the stderr messages hence it failed. The shortcut to remembering this is

executable  > some_file 2>&1

Hope this helps, Best regards, Tom.

like image 27
t0mm13b Avatar answered Sep 28 '22 17:09

t0mm13b


By the way, for reasons I do not completely understand, a think like

process.exe > result.txt 2<&1 

also seems to work

like image 33
Antoni Avatar answered Sep 28 '22 17:09

Antoni