get .bat to call other .bat?

N/a / NA
February 17, 2009 at 03:56:21
Specs: Windows Vista, C2D, 2GB
I'm trying to have a main batch file recurse through its subdirectories and call any batch files it encounters there. My problem is limiting the scope each batch to its own subdirectory.

say you have these files



So, batch.bat should call batch_deletes_txt.bat which deletes file1.txt only (not file3.txt), and batch.bat should also call batch_deletes_doc.bat which deletes file4.doc only (not file2.doc).

My contents:

for /r %%X in (*.bat) do if NOT %%X == %0 %%X
REM ^ the "if not" is to prevent infinite loops.

for /r %%X in (*.txt) do del "%%X"

for /r %%X in (*.doc) do del "%%X"

This doesn't work because the scope of each script is c:\temp, ie. not local. How do I fix this?

(My real goal is not deleting files, this is just an example)

See More: get .bat to call other .bat?

Report •

February 17, 2009 at 04:10:07
Replace your first command with this version:

for /r %%X in (*.bat) do if NOT "%%X" == "%~f0" (cd %%~pX && call "%%X")

The for /r command returns all files with fully qualified pathnames, so I am testing against %~f0 which expands the current batch file to its fully qualified pathname.

I am then changing to each batch file's directory before calling it, using the CALL command so that the current batch file doesn't terminate.

I have quotes around pathnames in case they contain spaces.

Caveat: I have not tested this.

Report •
Related Solutions

Ask Question