2

I'm working on some Windows .bat files that have been around for a long time. On their last line, they have a single exit statement without arguments.

This appears to be completely redundant to me. Is there any valid reason for their presence?

Bart van Heukelom
  • 43,244
  • 59
  • 186
  • 301

1 Answers1

4

An exit withoput /b option will exit batch file and the cmd.exe instance.

When you start the batch file by starting it from the explorer, there is not difference,
but when you start the batch file from a cmd window, the window closes when the batch file executes the exit.

Normally you should avoid this, as it's annoying behaviour, you can't build another batch file calling this type of files, as the exit also cancels the calling batch file.

call myAnnoyingBatch.bat
echo This won't be displayed anymore

I only know one good reason for using exit at the end of a script.
When you build a drag&drop script that should be bullet proof , you need an exit to avoid problems with some filenames like cat&dog.png

Community
  • 1
  • 1
jeb
  • 78,592
  • 17
  • 171
  • 225
  • Ah, so there is a difference, but indeed, that would be annoying and I can't imagine why they were made this way, so I'll just remove them. – Bart van Heukelom Jun 28 '16 at 09:51
  • By the way, some of the files do get called from an overarching file, and it doesn't cause the issue you described. However, it's not using `call` but `start /B /wait`. Could there be any reason for that, other than to explicitly avoid the problem of the `exit` in the subfile? – Bart van Heukelom Jun 28 '16 at 09:53
  • I see `call` runs the script in the current process while `start` runs a new one (equivalent to _sourcing_ vs _executing_ in bash), with the expected results regarding variable lifetime and such. But variables are not used here, so not a factor. That also explains why exit in a `call`ed file would exit the calling process: because there's just the one process. – Bart van Heukelom Jun 28 '16 at 09:56
  • `start /b /wait` starts a parallel command, the output shall be in the same window (`/b`) and wait until the parallel command finishes '(`/wait`). That could be replaced by a simple `cmd /c`. Or even with a `CALL` when you remove the `exit`, then the other scripts can also change environment variables of the caller context – jeb Jun 28 '16 at 09:59