我的批处理文件有问题。 它通过执行以下操作自动构建多个程序:
- 设置一些编译标志
- 运行'gmake all'
- 调用“检查错误级别”函数,如果错误级别为1,则退出
所以看起来像这样:
set FLAG=1
...
gmake all
call :interactive_check
set OTHERFLAG=1
...
gmake all
call :interactive_check
其中有 6 或 7 个(并且可能会增加)。所以我做了一个函数来检查错误级别,而不是在每一步都复制/粘贴它。 问题是这样的:错误检查是通过一个函数进行的:
:interactive_check
if errorlevel 1 (
echo.
echo /!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\
echo Error in compilation process... exiting
echo /!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\
echo.
cd %root_dir%
exit /B 1
) ELSE (
echo.Continuing to next step
)
goto:eof
现在,当运行它时,exit/B 1
只是退出函数,但不是批处理文件。
你知道如何退出完整的批处理文件而不必在每一步都复制/粘贴我的“if errorlevel 1..”吗?
最佳答案
对于一个好的解决方案,请参阅部分改进版本
您可以随时停止批处理,也可以在嵌套函数调用中停止。
你只需要创建一个语法错误,例如用一个空 block ()
,来抑制错误信息,它可以在调用中执行,调用的stderr被重定向为空。
@echo off
setlocal enabledelayedexpansion
rem Do something
call :interactive_check
rem Do something
call :interactive_check
goto :eof
::::::::::::::::::::::::::
:interactive_check
if errorlevel 1 (
echo.
echo /!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\
echo Error in compilation process... exiting
echo /!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\
call :halt 1
) ELSE (
echo.Continuing to next step
)
goto :eof
:: Sets the errorlevel and stops the batch immediately
:halt
call :__SetErrorLevel %1
call :__ErrorExit 2> nul
goto :eof
:__ErrorExit
rem Creates a syntax error, stops immediately
()
goto :eof
:__SetErrorLevel
exit /b %time:~-2%
goto :eof
2017-04-09改进版:只退出当前批处理,不退出调用批处理
正如@dbenham 提到的,有一种异常处理新技术也可用于仅退出当前批处理。
@echo off
echo Do something, detecting some fatal error
call :ExitBatch 3
exit /b
:ExitBatch [errorcode] - Exits only the current batch file, regardless how many CALLs
set _errLevel=%1
REM *** Remove all calls from the current batch from the call stack
:popStack
(
(goto) 2>nul
setlocal DisableDelayedExpansion
call set "caller=%%~0"
call set _caller=%%caller:~0,1%%
call set _caller=%%_caller::=%%
if not defined _caller (
REM callType = func
rem set _errLevel=%_errLevel%
goto :popStack
)
(goto) 2>nul
endlocal
cmd /c "exit /b %_errLevel%"
)
echo NEVER REACHED
exit /b
关于windows - 从函数内部退出批处理脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3227796/