Search code examples
batch-filecmdexitexit-code

How to avoid exit of Windows cmd terminal if called command executes `exit`?


In a Windows cmd terminal, by cmd, I call command scripts (.cmd), but some of these does an exit [code] without the /B, whereby my Windows terminal is terminated.

How to avoid exit of Windows cmd terminal if called command executes exit without the /B?


Solution

  • You could invoke scriptname.cmd with cmd /c. That way exit will exit your cmd /c invocation, rather than the ancestral console process.

    Test1.bat:

    @echo off & setlocal
    
    echo Exiting.
    exit 0
    

    Test2.bat:

    @echo off & setlocal
    
    echo Invoking Test1.bat
    cmd /c Test1.bat
    
    echo Still running!
    

    Output of Test2.bat:

    Invoking Test1.bat
    Exiting.
    Still running!

    ... and the console window remains open.