1.

Solve : Do you really need EXIT at the end of a BAT file??

Answer»

I leave off EXIT, and the BAT file works fine.  I don't notice any problems.

Do I really need to have EXIT at the end of a BAT file?Why would you start a new Topic where noone knows what the issue is ? ?
If you start a batch script (file) from an already open command window (by typing its name and pressing ENTER), if the batch ends with EXIT, that window will close. Without an EXIT, the window will stay open.

If you start a batch by double CLICKING it in Windows Explorer, the window will close when the batch ends, whether there is an EXIT or not.

If you follow EXIT with a number, that is the exit code the script will leave behind as an errorlevel.

If you don't need any of this, you can omit EXIT.


Thanks!  When do you ever want to set an "exit code"? . . . Also, if the .BAT file ran, why would there be an error?

https://ss64.com/nt/exit.html

   exitCode   Sets the %ERRORLEVEL% to a NUMERIC number.
              If quitting CMD.EXE, set the process exit code no.Exit codes are useful for creating batch files that are expected to be CALLED by other batch files. The Exit Code can return INFORMATION that can be evaluated by the calling batch file, just as you can do with internal and external commands. Quote from: slack7639 on January 03, 2018, 11:26:44 AM

Thanks!  When do you ever want to set an "exit code"? . . . Also, if the .BAT file ran, why would there be an error?

Don't think of it as always an indication of an "error". Sometimes it is just an "exit code". Historically, going right back to MS-DOS in the Microsoft world, programs and scripts have been able to leave behind a code, that is a number, in memory, which another script or program can read. It was called "ERRORLEVEL" and the name has stuck.

Here are two simple EXAMPLE scripts. Put them both in the same folder and run test1.bat

(1) test1.bat
Code: [Select]echo off
echo Running test2.bat...
call test2.bat
echo Back from test2.bat
if %errorlevel% equ 255 echo Answer was "yes"
if %errorlevel% equ 128 echo Answer was "no"
pause
(2) test2.bat
Code: [Select]echo off
:loop
set /p a="Are you happy (answer y or n)? "
if /i "%a%"=="y" exit /B 255
if /i "%a%"=="n" exit /B 128
echo Answer y or n!
goto loop
You can catch errorlevels returned by other languages:

Put these in the same folder as each other and run test3.bat

(1) stringlen.vbs
Code: [Select]wscript.quit len(wscript.arguments(0))

(2) test3.bat
Code: [Select]echo off
:loop
set /p str="Enter a string: "
if "%str%"=="" echo String cannot be empty & goto loop
wscript stringlen.vbs %str%
echo String has %errorlevel% character(s)
pause This would be better... copes when string has spaces...

(2) test3.bat
Code: [Select]echo off
:loop
set /p str="Enter a string: "
if "%str%"=="" echo String cannot be empty & goto loop
wscript stringlen.vbs "%str%"
echo String has %errorlevel% character(s)
pause


Discussion

No Comment Found