The batch file foo.bat must be written as follows:
@echo off
call "%~dp0bar.bat" 2 3
echo Result is: %result%
pause
The batch file bar.bat must be written as follows:
@echo off
set "int1=%~1"
set "int2=%~2"
set /A result=int1 + int2
The batch file foo.bat calls batch file bar.bat which means after processing of bar.bat the Windows command processor continues processing foo.bat with next command in that batch file after command CALL. Both batch files are processed by same cmd.exe and share the same list of environment variables.
That is not the case on using start bar.bat as this results in starting one more cmd.exe with its own list of environment variables for processing the batch file bar.bat being executed parallel by second instance of cmd.exe while first instance of cmd.exe continues processing foo.bat immediately after starting second cmd.exe.
The batch file foo.bat could be also written as:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
call :DoMath 2 3
echo Result is: %result%
echo(
pause
exit /B
:DoMath
set "int1=%~1"
set "int2=%~2"
set /A result=int1 + int2
goto :EOF
Everything below DoMath is now a subroutine which can be called multiple times from main code of foo.bat.
It is important that the batch files do not contain exit without parameter /B which results always in exiting cmd.exe processing the batch independent on calling hierarchy and independent on how cmd.exe was started before executing the batch file.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
- call /?... explains also- %~dp0... drive and path of argument 0 which is the full path of the batch file always ending with a backslash.
- echo /?
- exit /?
- goto /?
- pause /?
- set /?
- setlocal /?
- start /?... not used anymore
See also: