Best practice for exiting batch file? [closed]

会有一股神秘感。 提交于 2020-06-27 08:46:06

问题


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?


回答1:


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 to exit /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.




回答2:


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.



来源:https://stackoverflow.com/questions/31574365/best-practice-for-exiting-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!