Tuesday, July 27, 2010

Batch file recursion...

Batch files make some things so easy some time that I say, "Oh yeah I'll just build it in a batch file"! Simple and fast! Most of the time, it works to my advantage. Unfortunately, sometimes I get too far down the rabbit hole. Should I have rewritten it in Qt? Maybe... but I didn't want to rewrite something that was even more untested than the solution that was already there! Which brings me to my problem of needing recursion....

Recursion in a batch file?! You must be crazy you say!

Unfortunately, I did one of those things where the system just became more and more complex and ultimately recursion was the simplest solution. The problem was that I need to check dependencies of archives within archives, but the archive processing code was all the same, so... why rewrite?

To further make things interesting, well... I needed a bunch of envars to act as local variables. I realized later of course that I could use SETLOCAL but instead i chose to just use cmd /c on itself. Effectively preserving inheritance of globals, and leaving envars that are set within in their own playground.

So ProcessArchive.bat would go and process an archive and SET a bunch of envars while scrubbing that archive it would find, YET ANOTHER ARCHIVE! So ProcessArchive.bat calls cmd /c ProcessArchive.bat on the archive it found... and so on and so forth until everything finally returned. Yay!

NOTE : %CD% does not expand in a FOR loop!

FOR /D %%V IN (*) (
    pushd %%v
    echo %CD%
    popd
)

%CD% will give you the CWD outside the FOR LOOP.  :(((

So if you want to get %CD% inside you're going to have to use the cmd /c trick.


FOR /D %%V IN (*) (
    cmd /c push_echo_pop.bat
)