Call a subroutine in a batch from another batch file -
file1.bat:
@echo off :test echo in file 1 call file2.bat (here want call demo routine in file2.bat) file2.bat:
:hello echo in hello :demo echo in demo from batch file1 want make call sub routine in batch file2.
tried example call file2.bat:demo didn't give correct result.
how can achieve this?
you can write functions file (in sample library.cmd)
@echo off setlocal enableextensions rem not directly called exit /b 9009 :test echo test [%*] goto :eof :test2 echo test2 [%*] goto :eof :testerrorlevel echo testerrorlevel exit /b 1 and caller batch can like
@echo off setlocal enableextensions disabledelayedexpansion call :test arg1 arg2 arg3 call :test2 arg4 arg5 arg6 call :testerrorlevel && echo no errorlevel || echo errorlevel raised goto :eof :test :test2 echo calling function %0 library.cmd %* :testerrorlevel echo calling function %0 library.cmd in case, labels need defined same name in both files.
the direct invocation of "library" batch file replace context of call :label, , when invoked batch readed, goto :label internally executed , code continues inside indicated label. when called batch file ends, context released , code after call :label continues.
edited
as jeb points in comments, there drawback in method. code running in called batch file can not use %0 retrieve name of function being called, return name of batch file. if needed, caller can shown in sample code.
edited 2016/12/27
answering dbenham, have no way know if coding error or intended feature, how process works
the lines in batch file processed inside inner batloop function when batch "context" created. function receives, 1 of arguments, pointer command caused "context" created.
inside function commands in batch file iterated. loop iterates on commands makes test in each iteration: if extensions enabled, first line in batch file , arguments of command started context starts colon (a label), goto generated jump label.
up here, have suppose intended behaviour handle call :label syntax: create new "context", load file, jump label.
but command argument received never changed, different variable used track execution of commands in batch file. if new batch file loaded / overwrites current batch "context" (we have not used call command), after loading new batch code, batloop resets line count (we start @ first line of loaded file) and, voila, condition @ start of loop (extensions enabled, first line, colon) true again (the pointed input command has not been changed) , new goto generated.
Comments
Post a Comment