I am trying to figure out how file1.bat can call file2.bat at a specified label.
I figured I can do it like this:
File1.bat
:config
As I said in the comment that I attached to my answer, I awarded the bounty, because @NicoBerrogorry took the time to devise an excellent solution, and provide a complete write-up.
Nevertheless, there was one syntax error that he overlooked, probably because he doesn't use CMD files, while I have almost entirely abandoned BAT files. The following CALLAT script incorporates one correction and four enhancements.
@ECHO OFF
SETLOCAL EnableDelayedExpansion
rem Create a folder in the temporary files directory.
IF NOT EXIST "%TEMP%\CALLAT\" MKDIR "%TEMP%\CALLAT\"
rem Chose a name for the modified script.
SET MODIFIED_SCRIPT="%TEMP%\CALLAT\modified_%1.bat"
rem Convert the called script name to the corresponding .bat
rem or .cmd full path to the called script.
rem Then load the script. - 2017/05/08 - DAG - The second if exist test duplicated the first. Instead, it must evaluate for the .CMD extension.
SET "COMMAND_FILE=%~dp0%1"
IF EXIST "%COMMAND_FILE%.bat" (
SET "COMMAND_FILE=%COMMAND_FILE%.bat"
) ELSE IF EXIST "%COMMAND_FILE%.cmd" (
SET "COMMAND_FILE=%COMMAND_FILE%.cmd"
) else if exist "%COMMAND_FILE%" (
echo INFO: Using "%COMMAND_FILE%"
) else (
echo ERROR: Cannot find script file %COMMAND_FILE%.bat
echo or %COMMAND_FILE%.cmd
)
rem Add some lines to go directly to the desired label.
ECHO @ECHO OFF> %MODIFIED_SCRIPT%
ECHO GOTO %2>> %MODIFIED_SCRIPT%
rem Append the called script.
copy %MODIFIED_SCRIPT%+%COMMAND_FILE% %MODIFIED_SCRIPT% > NUL:
rem Call the modified script.
CALL %MODIFIED_SCRIPT%
rem Pack out your trash. When a script ends, you get an ENDLOCAL for free.
del %MODIFIED_SCRIPT%
rd "%TEMP%\CALLAT\"
Finally, this version of CALLAT eliminates a redundant ECHO OFF and the concluding ENDLOCAL, which I discovered long ago is unnecessary, because exiting a script implies ENDLOCAL.
Since virtually all of my production scripts inhabit a single directory that is accessible via the PATH directory list, the requirement that both scripts inhabit the same directory isn't a significant hindrance. Moreover, with a little more work, it could almost certainly be relaxed. I'll leave that as an exercise for interested readers, but I'll give you one clue; it might involve calling an internal subroutine that can parse the name of the input file by leveraging the technique described [in Command Line Parameters].1
The script shown above is about to find its way into production.