Redirect stdout and stderr from inside a batch file

sashoalm picture sashoalm · Nov 15, 2012 · Viewed 25.9k times · Source

Is there a way to redirect stdout and stderr for a batch file from inside it.

I'm imagining something like

set STDOUT=stdout.log
echo Some text
a.exe
b.exe
c.exe

Where both Some text, and the output of a.exe, b.exe and c.exe would go to stdout.log

Is this possible?

Answer

dbenham picture dbenham · Nov 15, 2012

It is more efficient to redirect once for the entire collection of commands than it is to redirect (with append) each individual command. It takes time to intialize the redirection. It may not be noticable for a few redirected commands, but if done in a loop with many iterations, it can become quite significant.

One method is to enclose the entire block of redirected commands within parentheses and redirect outside the parentheses

>stdout.log 2>&1 (
  echo Some text
  a.exe
  b.exe
  c.exe
)

Another option is to put your commands in a subroutine and redirect the CALL

call :redirect >stdout.log 2>&1
exit /b

:redirect
echo Some text
a.exe
b.exe
c.exe
exit /b