Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Batch Functions in another batch file

Tags:

batch-file

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.

like image 571
Jared Allard Avatar asked Nov 05 '13 20:11

Jared Allard


People also ask

Can you call a batch file from another batch file?

Simply entering a batch file's name within another batch file will run the batch file you want to call. However, after the called batch file completes, it won't pass control back to the calling batch file.

What does %% A do in batch?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

What is @echo in batch file?

To display the command prompt again, type echo on. To prevent all commands in a batch file (including the echo off command) from displaying on the screen, on the first line of the batch file type: Copy. @echo off.

Can you use UNC path in batch file?

You can only reference UNC paths in file and folder commands. IS allowed at a prompt or in a batch file.


2 Answers

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
like image 124
npocmaka Avatar answered Sep 19 '22 07:09

npocmaka


@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?

like image 41
Aacini Avatar answered Sep 20 '22 07:09

Aacini