13

Alright, so lets say we have a file called "lib.cmd" it contains

@echo off
GOTO:EXIT

:FUNCTION
     echo something
GOTO:EOF

:EXIT
exit /b

Then we have a file called "init.cmd" it contains

@echo off

call lib.cmd

Is there anyway to access :FUNCTION inside of init.cmd? Like how bash uses "source" too run another bash file into the same process.

Jared Allard
  • 726
  • 8
  • 33

3 Answers3

21

Change your lib.cmd to look like this;

@echo off
call:%~1
goto exit

:function
     echo something
goto:eof

:exit
exit /b

Then the first argument passed to the batch file (%~1) will identify as the function you want to call, so it will be called with call:%~1, and now you can call it in init.cmd in this way:

call lib.cmd function
zvava
  • 91
  • 1
  • 2
  • 14
npocmaka
  • 51,748
  • 17
  • 123
  • 166
4
@echo off

(
rem Switch the context to the library file
ren init.cmd main.cmd
ren lib.cmd init.cmd
rem From this line on, you may call any function in lib.cmd,
rem but NOT in original init.cmd:
call :FUNCTION

rem Switch the context back to original file
ren init.cmd lib.cmd
ren main.cmd init.cmd
)

For further details, see How to package all my functions in a batch file as a seperate file?

Community
  • 1
  • 1
Aacini
  • 59,374
  • 12
  • 63
  • 94
0

The following takes @npocmaka solution and add support for calling functions in with arguments. Thanks @jeb for improvements. Let's save the following as lib.cmd:

@echo off
shift & goto :%~1

:foo
set arg1=%~1
set arg2=%~2
echo|set /p=%arg1%
echo %arg2%
exit /b 0

You can test it with:

call lib.cmd foo "Hello World" !

And it will print Hello World!.

ceztko
  • 13,391
  • 2
  • 44
  • 64