How do I call a subroutine in a batch file?
John Savill
January 8, 2000
1 Min Read
[Editor’s Note: Some or all of the following FAQ text was submitted by readers, Rob Warner and Ian Hamilton.]
A. An easy solution is to have the batch file call itself recursively and pass itself a couple of parameters, as the following example illustrates.
@echo off
if (%1)==(Recurse) goto Recurse
goto Begin
:Begin
echo Batch file begins.
call %0 Recurse test
goto End
:Recurse
echo This is a recursive call.
echo The parameters received were "%1" and "%2".
goto Clean-End
:End
echo Finished.
:Clean-End
Be careful using this method, because recursive batch files can be dangerous if your subroutine fires off another program. The following example illustrates an alternative method.
:Begin
echo start subroutine
call :Subroutine
echo finished subroutine
goto End
:Subroutine
echo In subroutine
goto :EOF
:End
The following example illustrates yet another method, which you can use on Windows NT .cmd files. Note the syntax for calling subroutines (with parameters) and the special construction for returning (i.e., goto :eof).
@echo off
call :Begin
echo Finished.
goto :eof
:Begin
echo Batch file begins.
call :recurse Recurse test
goto :eof
:Recurse
echo This is a recursive call.
echo The parameters received were "%1" and "%2".
goto :eof
About the Author
Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.
You May Also Like