Johan Åhlgren

Redirecting output from a batch file

For the projects I plan to upload, I am currently creating a simple make file, in the form of a batch file, whose job is to build all my projects. I want it to execute the command-line compiler (currently Delphi’s, but we may see others in the future) to produce my binaries. I want to redirect all output to a file, instead of sending it to the standard output. In a batch file, I can redirect pretty much everything (echo, compile messages etc.) using the redirection operator, “>”. But what if I want to redirect everything in the batch file to a file, without having to use “>” everywhere?

Well, I can of course create my “MakeAll.bat” and then another one with only one line: “MakeAll.bat > MakeAll.log”. That would give me two batch files, where the second one really does close to no job of its own. However, with a litte trick, I can build this functionality into MakeAll.bat itself, by letting it call itself, and redirecting its output:

echo off
if [%1] NEQ [] goto :execute 
call MakeAll.bat X > MakeAll.log
goto :end


echo ---------- Building Tokenizer ----------
pushd ProjectsProject1Parsing
dcc32 -B -Q Tokenizer.dpr


When I execute MakeAll.bat, e.g. by double-clicking it, no parameters are passed to it. This means that the line “if [%1] NEQ [] goto :execute” will not cause a jump to “:execute” – the condition is fullfilled only if parameter 1 (the [%1] part) is not empty (the [] part). Thus, we will continue to the next line, where the batch file calls itself again – this time with parameter “X” and its output redirected to “MakeAll.log”. Once this is done, the “first instance” goes to “:end” and exits. The “second instance” starts, and since the first parameter now equals “X”, it will jump to “:execute”, perform what we want it to perform (sending all output to MakeAll.log) and exit.

Leave a Reply

Your email address will not be published.