14

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.

4

3 回答 3

21

改变你lib.cmd的样子;

@echo off
call:%~1
goto exit

:function
     echo something
goto:eof

:exit
exit /b

%~1那么传递给批处理文件的第一个call:%~1参数init.cmd

call lib.cmd function
于 2013-11-05T21:00:03.687 回答
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
)

有关更多详细信息,请参阅如何将批处理文件中的所有函数打包为单独的文件?

于 2013-11-05T23:33:00.407 回答
0

以下采用@npocmaka 解决方案并添加对使用参数调用函数的支持。感谢@jeb 的改进。让我们将以下内容另存为lib.cmd

@echo off
shift & goto :%~1

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

您可以使用以下方法对其进行测试:

call lib.cmd foo "Hello World" !

它会打印出来Hello World!

于 2021-03-30T13:45:41.370 回答