Redirecting Output from within Batch file

The simple naive way that is slow because it opens and positions the file pointer to End-Of-File multiple times.

@echo off
command1 >output.txt
command2 >>output.txt
...
commandN >>output.txt

A better way – easier to write, and faster because the file is opened and positioned only once.

@echo off
>output.txt (
  command1
  command2
  ...
  commandN
)

Another good and fast way that only opens and positions the file once

@echo off
call :sub >output.txt
exit /b

:sub
command1
command2
...
commandN

Edit 2020-04-17

Every now and then you may want to repeatedly write to two or more files. You might also want different messages on the screen. It is still possible to to do this efficiently by redirecting to undefined handles outside a parenthesized block or subroutine, and then use the & notation to reference the already opened files.

call :sub 9>File1.txt 8>File2.txt
exit /b

:sub
echo Screen message 1
>&9 echo File 1 message 1
>&8 echo File 2 message 1
echo Screen message 2
>&9 echo File 1 message 2
>&8 echo File 2 message 2
exit /b

I chose to use handles 9 and 8 in reverse order because that way is more likely to avoid potential permanent redirection due to a Microsoft redirection implementation design flaw when performing multiple redirections on the same command. It is highly unlikely, but even that approach could expose the bug if you try hard enough. If you stage the redirection than you are guaranteed to avoid the problem.

3>File1.txt ( 4>File2.txt call :sub)
exit /b

:sub
etc.

Leave a Comment