Why does calling a nested batch file without prepending “call” to the line exit the parent batch file?

前端 未结 3 1524
挽巷
挽巷 2020-12-17 07:45

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:

  • CALL
相关标签:
3条回答
  • 2020-12-17 08:33

    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!

    0 讨论(0)
  • 2020-12-17 08:37

    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.

    0 讨论(0)
  • 2020-12-17 08:40

    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).

    0 讨论(0)
提交回复
热议问题