退出批处理文件的最佳做法?

Best practice for exiting batch file?

对于批处理文件,我想检查不同的条件并获得帮助消息

哪一个是显示消息后退出批处理文件的最佳做法?

if "%1"=="/?"(
  echo "help message"
  exit /b 0
)
[more code]

if "%1"=="/?"(
  echo "help message"
  goto :EOF
)
[more code]
:EOF

对于我未经训练的人来说,第一个似乎更好,但很多在线示例都使用 GOTO 标记方法

SO 社区对此有何看法?

我个人使用 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 

将打印:

Errorlevel: 1
press any key to continue...

在创建可能会失败的批处理脚本时,使用此方法设置错误级别非常有用。您可以为不同的错误创建单独的 :labels,并使每个 return 具有唯一的错误级别。

  • 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.

两者也可以在同一个批处理文件中同时使用:

@echo off
call :getError
echo %errorlevel%
pause
goto :eof

:getError 
exit /b 2

另一种退出批处理脚本的方法是使用 cmd /k 当在独立的批处理文件中使用时,cmd /k 将 return 您进入常规命令提示符。

总而言之,我建议使用 exit,因为您可以设置错误级别,但是,这完全取决于您。

GOTO :EOF 与 EXIT /B 之间没有功能或性能差异,只是 EXIT /B 允许您指定 returned ERRORLEVEL,而 GOTO :EOF 则不允许。

显然,如果您想在 return 时指定 ERRORLEVEL,则首选 EXIT /B。

如果您不关心 return 代码,或者您知道 ERRORLEVEL 已经设置为正确的值,那么它没有任何区别 - 这完全是偏好/编码风格的问题.