8

I would like to set the standard output of a batch script to go to a file. I would like to do this inside the script if possible.

Note: I do not want to do this: foo.bat > StdOut.txt

I would like to do something inside the script to redirect the output to a file
For example:

foo.bat

:: Redirect standard output to StdOut.txt
:: Insert batch code to do what I want here.
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184

2 Answers2

16

One way of doing it is the following. Use the call command to execute a label in the script. Edit I realized the first version I posted does not seem to work in a cmd.exe prompt (I was using TCC). The following seems to work in both command processors:

@echo off
call :testitout > t.tmp
goto:eof

:testitout
echo Hi There
echo Goodbye
Community
  • 1
  • 1
Mark Wilkins
  • 40,729
  • 5
  • 57
  • 110
  • 1
    @SwDevMan81, The reason I looked is because I have wanted to do this in the past and never knew how. But your question prompted my brain to remember that the call command could call a label in the batch file, which made me wonder if this trick would work. So I only just now learned this. – Mark Wilkins Jan 05 '11 at 18:19
  • Yeah I definitely wont have thought of this. Looks like we both learned something new today :) – SwDevMan81 Jan 05 '11 at 18:55
  • I think you also have to redirect error output to standard output to see everything. – HiredMind Nov 15 '13 at 23:57
  • It's great, but there is a number of problems with this solution, especially if you're converting an existing script: * Utilities that detect redirection and behave differently (e.g., `more`) will think they are run interactively * Positional variables that contain arguments to the script will not be available after the `call` unless you explicitly `call :testitout %*` May be there are more. The first one is currently driving me nuts... Anyone got a solution for that? I can't think of anything better than running `more /p >&2` when redirecting as `call :testitout >t.tmp 2>&1`. – Alexander Amelkin Oct 06 '16 at 12:11
1

> is the standard, so you're more-or-less stuck with that; however, you can move it inside the batch file:

foo.bat:

@echo off
@echo Start File > StdOut.txt
@dir >> StdOut.txt
@echo End File >> StdOut.txt
Chris Adams
  • 1,067
  • 8
  • 15