views:

416

answers:

5

As a long time UNIX shell scripter / release engineer coming into the Windows environment full time with my latest job, there are some things I inevitably miss.

One of them is my trusty old 'exec 2>&1' which in the Bourne shell permently knots together stderr and stdout for the duration of the script, so that logging will capture everything good and bad.

I realize you can append 2>foo.log to the end of every command line invocation, but I'm wondering if there's a better way.

Is there any equivalent in the Windows environment? We're using both .BAT file scripts and Perl scripts here (Mostly for build automation but also some other things) and I'd dearly love to know if this is possible at all.

A: 

Read this KB article from MS. Sample taken from the said article:

You can print the errors and standard output to a single file by using the "&1" command to redirect the output for STDERR to STDOUT and then sending the output from STDOUT to a file:

 dir file.xxx 1> output.msg 2>&1
dirkgently
Thanks but I don't think you read the question. I know I can redirect stdout and stderr for each command invocation, what I want is to do said redirect for the duration of a script.
feoh
My point was: I don't see any problem using the above with a script. However, AFAIK, there is no special STDERR for batch files.
dirkgently
Perl scripts should work just fine though.
dirkgently
+5  A: 

In Perl you can do

open STDERR, '>&STDOUT' or die "Can't dup STDOUT";

to redirect the STDERR output of the script to STDOUT. See the open documentation for more info. I wouldn't expect this to effect the output of system calls, i.e. system or backticks.

Michael Carman
It does affect the output of system calls and backticks. Those subprocesses get whatever STDIN, STDOUT and STDERR handles are open in Perl at the time they are called.
xdg
+2  A: 
RBerteig
A: 

The 2>&1 thing seems to be working for me for scripts:

testcmd.cmd > stdboth.txt 2>&1

What exactly are you doing and what are you expecting when you're doing it?

Michael Burr
Thanks but as I said in the question, I'm looking for something that redirects stderr to stdout for the *entire script* - not just a single command invocation.
feoh
I'm not sure what you mean by 'entire script' - in the above example stdout and stderr seem to be redirected for all the commands in the testcmd.cmd script (and any scripts it calls). The commands within the script do not need to be modified.
Michael Burr
+1  A: 

You can apply redirection to command blocks as well as single commands

(
echo 1
dir
echo 2
) >somefile.txt

Note that it is impossible to use labels and goto inside of command blocks, though.

mihi