batch-filecmdcommand-linecall

To "Call" or "Not to Call" a batch file?


If from inside a bat file you called another batch file but still had a few remaining operations to complete, how can you make sure that the call to first bat file will after completion or error, will return to the file that called it in the first instance?

Example:

CD:\MyFolder\MyFiles
Mybatfile.bat

Copy afile toHere

or

CD:\MyFolder\MyFiles
CALL Mybatfile.bat

COPY afile toHere

What is the difference between using CALL or START or none of them at all? Would this have any impact on whether it would return for the results of the copy command or not?


Solution

  • As others have said, CALL is the normal way to call another bat file within a .bat and return to the caller.

    However, all batch file processing will cease (control will not return to the caller) if the CALLed batch file has a fatal syntax error, or if the CALLed script terminates with EXIT without the /B option.

    You can guarantee control will return to the caller (as long as the console window remains open of course) if you execute the 2nd script via the CMD command.

    cmd /c "calledFile.bat"
    

    But this has a limitation that the environment variables set by the called batch will not be preserved upon return.

    I'm not aware of a good solution to guarantee return in all cases and preserve environment changes.

    If you really need to preserve variables while using CMD, then you can have the "called" script write the variable changes to a temp file, and then have the caller read the temp file and re-establish the variables.