Routines / functions / methods in .bat

April 19, 2010 at 03:08:09
Specs: Windows XP
Is that possible? To create a function e.g. FUNC1 which is getting evaluated several times in the script - and after evaluation the program continues on the same position where the function was called?

E.g.:

echo test
call :FUNC1
echo test2

:FUNC1
echo In function
echo want to go back now

Now I want to continue at test2 (next command should be echo test2) without creating another label before "echo test2" as I need to call the method several times in the script, not only once!

Thanks for your help!


See More: Routines / functions / methods in .bat

Report •

#1
April 19, 2010 at 05:46:49
You have answered your question by yourself. What you posted is exactly how functions/procedures need to be coded in a batch script.

Code the subroutines at the end of your script and end each one by a goto :EOF the RETURN statement for batch. More you can pass arguments to subroutines and refer to those by %1 %2 and so on. E.G.

echo test
call :FUNC1 ALPHA BETA
echo test2

goto :EOF [Return to OS]

:FUNC1 
echo In function FUNC1 %1 %2
echo want to go back now
goto :EOF [Return to Main]


Report •

#2
April 19, 2010 at 08:10:22
Thanks a lot, that worked out perfectly fine! :)
I assume that in case I add an exit /B 1 in the function that the program continues where I called the function and have errorlevel 1 there? Or will it quit immediately?

Report •

#3
April 19, 2010 at 09:17:29
As you correctly said the program returns to the statement following the call and sets the ErrorLevel. The exit /B [errorlevel] is just an alternate RETURN statement instead of goto :EOF.

Report •
Related Solutions


Ask Question