Reputation: 940
I understand how to call nested batch files from within a parent file using the call
command, as there are plenty of resources on that:
However, I don't understand why calling another batch file from another terminates the parent.
For a less abstract example, suppose I have a batch file that "links" together separate batch files, and I erroneously didn't prepend call
to each line:
foo.bat
bar.bat
This would only execute foo.bat and then exit. To correctly execute both commands, I would have to prepend call before each statement:
call foo.bat
call bar.bat
Why does the first functionality still exist? Why hasn't it been changed? I noticed that call
was introduced in MS-DOS 3.3, which was released in the late 1980s, so is this functionality still here for reverse compatibility?
I can't think of any (practical) usages of it, but perhaps I'm too used to "new" programming techniques.
Upvotes: 38
Views: 26436
Reputation: 82267
As Sean Cheshire wrote, it's necessary for backward compatibility.
But starting a batch file from a batch file without using CALL
does not terminate the parent!
It looks that way, as the parent normally will not executed further after the second batch exits.
But using a call before starting the second.bat, will show that the first batch isn't terminated.
parent.bat
echo parent.bat
call :myLabel
echo back in parent.bat main
exit /b
:myLabel
second.bat & echo back in parent.bat
exit /b
second.bat
echo second.bat
exit /b
I use here the the secpond.bat & echo back ...
to avoid another bug/feature of cmd.exe.
If you use second.bat
without any extras it will start second.bat
AND jump to the label :myLabel
in second.bat
!
Upvotes: 8
Reputation: 15923
DOS used simple text processing (back when you had things like FILES=20
in config.sys to allow 20 file handles), so opened the file, read the next line, closed the file, then executed the line just read. If the file called another, then the processing continued with that file, so only 1 file handle would be required for a batch file.
Until Microsoft put in the call
command, there was no way to get back to the original file (without using tricks like giving the name of the previous file as a parameter, and using temporary files to let the original batch file know it had dome some processing, and could then GOTO
the next part of the file).
Upvotes: 37
Reputation: 125671
Call
is basically saying "go execute this other batch file, and then come back here and continue". It has been there since DOS 3.3 or so, and if it were removed now would break all backward-compatibility (which is why people are still using batch scripts). It can also be used to branch to :link
locations.
For info on the use and syntax (for future reference for others), you can see this MS TechNet link
If you need new functionality, use CMD scripts or PowerShell scripts instead.
Upvotes: 0