Accessing Batch Functions in another batch file

断了今生、忘了曾经 提交于 2021-02-06 10:15:08

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/19798777/accessing-batch-functions-in-another-batch-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!