Reply to comment

Batch tricks: Creating libraries

You can call other batch files via the call command and pass parameters as well. Well, suppose you have a plethora of useful functions but you don't want a batch file for each of them or copy them into all batches that use them.

With a simple pattern you can concentrate them into one batch file. I've prepared this here, along with a bit of stuff you might need to do to ensure it's working:

rem jump target, so we can shift without hesitation
set target=%1
rem throw away target to give subroutines access to %1, …
shift
rem prepare a human-friendly list of parameters
call :get_param_list %
goto %target%
:foo
echo Foo called with parameters: %PARAMS%
goto :EOF
:bar
echo Bar called with parameters: %PARAMS%
goto :EOF
:get_param_list
rem account for the first one which has to be discarded due to %

shift
rem we need delayed expansion, but only here
setlocal enableextensions enabledelayedex­pansion
:get_param_lis­t_loop
set PARAMS=%PARAM­S%, %1
shift
if not%1“=="" goto get_param_list_loop
rem strip the first comma
set PARAMS=%PARAM­S:~2%
endlocal & set PARAMS=%PARAMS%
goto :EOF

The code above consists of a bit initialization code, namely the set target=%1 and shift to get the label we want to jump to and return everything to normal for the following code. The get_param_list is mainly there so we have some weird code to look at and have a bit of debugging stuff in place for testing. The rest are labels that mark the subroutines, ending with a goto :EOF each. The batch itself is nothing more than some kind of switch statement, selecting the function to execute with the first parameter.

Calling a function is pretty easy, then (assuming our batch above was named lib.cmd):
call lib foo param1 param2 param3 …
which will yield the following output:
Foo called with parameters: param1, param2, param3, …

Voilà, we got some kind of libraries or namespaces. If you want, you can nest them, I leave that as an exercise for the reader.

Reply

The content of this field is kept private and will not be shown publicly.