Geo
Geo

Reputation: 96797

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?

Upvotes: 5

Views: 2904

Answers (3)

Antoni
Antoni

Reputation: 2622

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

process.exe > result.txt 2<&1 

also seems to work

Upvotes: 1

t0mm13b
t0mm13b

Reputation: 34592

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.

Upvotes: 2

developmentalinsanity
developmentalinsanity

Reputation: 6229

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.

Upvotes: 8

Related Questions