For a batch file I want to check for different conditions and have a help message
Which one is the best practice for exiting the batch file after displaying the message?
if "%1"=="/?"(
echo "help message"
exit /b 0
)
[more code]
or
if "%1"=="/?"(
echo "help message"
goto :EOF
)
[more code]
:EOF
The first one seems better for my untrained eyes but a lot of the examples online use the GOTO
tag method
What is the SO community's opinion on this?
Personally I use exit
.
The normal
exit
command simply terminates the current script, and the parent (for example if you were running a script from command line, or calling it from another batch file)
exit /b
is used to terminate the current script, but leaves the parent window/script/calling label open.With exit, you can also add an error level of the exit. For example,
exit /b 1
would produce an%errorlevel%
of 1. Example:
@echo off
call :getError rem Calling the :getError label
echo Errorlevel: %errorlevel% rem Echoing the errorlevel returned by :getError
pause
:getError
exit /b 1 rem exiting the call and setting the %errorlevel% to 1
Would print:
Errorlevel: 1
press any key to continue...
Setting error levels with this method can be useful when creating batch scripts that may have things that fail. You could create separate :labels
for different errors, and have each return a unique error level.
goto :eof
ends the current script (call) but not the parent file, (similarly toexit /b
)- Unlike exit, in which you can set an exiting errorlevel,
goto :eof
automatically sets the errorlevel to the currently set level, making it more difficult to identify problems.
The two can also be used in unison in the same batch file:
@echo off
call :getError
echo %errorlevel%
pause
goto :eof
:getError
exit /b 2
Another method of exiting a batch script would be to use cmd /k
When used in a stand-alone batch file, cmd /k
will return you to regular command prompt.
All in all i would recommend using exit
just because you can set an errorlevel, but, it's really up to you.
There is no functional or performance difference between GOTO :EOF vs EXIT /B, except that EXIT /B allows you to specify the returned ERRORLEVEL, and GOTO :EOF does not.
Obviously if you want to specify the ERRORLEVEL when you return, then EXIT /B is preferred.
If you don't care about the return code, or you know that the ERRORLEVEL is already set to the correct value, then it makes no difference - it becomes strictly a matter of preference / coding style.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With