Is it possible to redirect the output of a batch file inside the script?

12,743

Solution 1

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

Solution 2

> 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
Share:
12,743
SwDevMan81
Author by

SwDevMan81

Twitter: @SwDevMan81 Mail: SwDevMan81 at Gmail Feel free to ping me for any questions you have. Job Title: Software Engineer Job Develop: Software for radar systems, Software GUI, real time embedded Current Languages: C#, C++, Java AS: Monroe Community College (Engineering Science) BS: University at Buffalo (Computer Science) MS: University at Buffalo (Computer Science & Engineering) MBA: Syracuse University (Business Analytics) Sites: Design Patterns Salt

Updated on June 17, 2022

Comments

  • SwDevMan81
    SwDevMan81 almost 2 years

    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
    SwDevMan81 over 13 years
    Thanks, this was exactly what I was looking for
  • Mark Wilkins
    Mark Wilkins over 13 years
    @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.
  • SwDevMan81
    SwDevMan81 over 13 years
    Yeah I definitely wont have thought of this. Looks like we both learned something new today :)
  • HiredMind
    HiredMind over 10 years
    I think you also have to redirect error output to standard output to see everything.
  • Alexander Amelkin
    Alexander Amelkin over 7 years
    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.