4

I have a .bat which emits "Exit 1" in case of failure, this is closing the cmd window and prevents user to see the details of error.

I would like to force cmd to stay opened to see the messages.

I know that I could have used EXIT /B 1 in .bat to not close the cmd automatically, but only interrupt the script.

/B        When used in a batch script, this option will exit 
          only the script (or subroutine) but not CMD.EXE
          If executed on the command-line it will close CMD.exe

But the .bat is generated by a tool, so I can't simply modify it. Obviously, for the same reason I can't just add "PAUSE" in it.

I also know about "cmd /k" which avoids to close cmd after to have run a script, but it just keeps the cmd open once a script is successfully executed, if an "EXIT" function is emitted, it does not prevent cmd to close.

2 Answers 2

3

If your CMD calls the batch with another CMD /C xyz.bat then the exit 1 inside the bat file should not close the original CMD window, and the /C ensures that sub-CMD will close itself at the end of the BAT file if no exit was reached.

Then you can check error level for the batch and deal with whatever action you want in the top level CMD - such as timeout /t 10 && exit if you want that to close after giving user time to read the error message:

cmd /c a.bat
IF %ERRORLEVEL% NEQ 0 (echo ERROR && timeout /t 10 && exit)
1
  • CMD /C xyz.bat works perfectly ! Thanks a lot for this trick :).
    – AFract
    Mar 26, 2021 at 10:39
0

Why not use something like:

if not defined !var! (
  echo Source folder missing^^!
  goto :eof
)

Exits the batch file but does not exit CMD. The same as batch functions are made.

3
  • Hello, it looks like a change to do in the batch itself. Like I said in first post, it's not an option because the .bat is generated by a tool. Running the batch itself with cmd /C like suggested previously worked very well. Thanks anyway :)
    – AFract
    Sep 2, 2021 at 7:40
  • 1
    Ahh.. This is the case then. Didn't notice ;) gg. Sep 14, 2021 at 5:57
  • No problem my friend :)
    – AFract
    Sep 14, 2021 at 7:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .