使用方法
我有一个很大的批处理文件,其中有许多有用的功能。
我想将其中一些函数放在单独的文件中,而有时我希望将它们放在一个包含文件中,这样整个脚本就是一个文件。
我想知道,由于 CALL 命令即使在调用标签时也会检查磁盘中的某些内容,因此是否存在可以覆盖内部标签的文件。
以下是测试方法。
在新文件夹中,首先测试脚本labelorfile.bat
@echo off
echo starting test
echo we call the label :mytestfunction
call :mytestfunction
echo this is after "call :mytestfunction" in file labelorfile.bat
echo we call the file mytestfunction.bat
call mytestfunction.bat
echo this is after "call mytestfunction.bat" in file labelorfile.bat
call mytestfunction
echo this is after "call mytestfunction" in file labelorfile.bat
goto :eof
:mytestfunction
echo this is the label :mytestfunction in the labelorfile.bat file
goto :eof
下一个文件,单行批处理文件,mytestfunction.bat
echo this is the file mytestfunction.bat
下一个文件,无扩展名的单行批处理文件,mytestfunction
echo this is the file mytestfunction with no extension
我运行labelorfile.bat,这是输出
labelorfile.bat
starting test
we call the label :mytestfunction
this is the label :mytestfunction in the labelorfile.bat file
this is after "call :mytestfunction" in file labelorfile.bat
we call the file mytestfunction.bat
this is the file mytestfunction.bat
this is after "call mytestfunction.bat" in file labelorfile.bat
this is the file mytestfunction.bat
this is after "call mytestfunction" in file labelorfile.bat
结论,带有标签名称的文件不能覆盖批处理文件中的标签
这是正确的吗?
正如您的测试证明,
call :label
always调用本地标签,而call file
always调用外部文件.bat;没有办法“覆盖”这种行为......
但是,我认为解决您问题的方法可能是检查是否调用本地标签导致错误,在这种情况下,调用外部文件:
@echo off
setlocal
echo Calling 1:
call :localLabel1
echo Calling 2:
call :localLabel2 2> NUL
if errorlevel 1 (
echo :localLabel2 don't exist. Calling the external file:
call localLabel2
)
goto :EOF
:localLabel1
echo I am local subroutine 1
exit /B
这是localLabel2.bat文件:
echo I am the separate file localLabel2.bat
这是输出:
Calling 1:
I am local subroutine 1
Calling 2:
:localLabel2 don't exist. Calling the external file:
I am the separate file localLabel2.bat