如何在调用循环中完全停止批处理文件?
exit/b
只是退出 :label 循环,而不是整个批处理文件,而 bare exit
退出批处理文件 和 父 CMD外壳,这是不需要的。
@echo off
call :check_ntauth
REM if check fails, the next lines should not execute
echo. ...About to "rmdir /q/s %temp%\*"
goto :eof
:check_ntauth
if not `whoami` == "nt authority\system" goto :not_sys_account
goto :eof
:not_sys_account
echo. &echo. Error: must be run as "nt authority\system" user. &echo.
exit /b
echo. As desired, this line is never executed.
结果:
d:\temp>whoami
mydomain\matt
d:\temp>break-loop-test.bat
Error: must be run as "nt authority\system" user.
...About to "rmdir /q/s d:\temp\systmp\*" <--- shouldn't be seen!
最佳答案
您可以从 :not_sys_account
子例程中设置 ERRORLEVEL
并将其用作返回值。主程序可以检查这一点并改变它的行为:
@echo off
call :check_ntauth
REM if check fails, the next lines should not execute
if errorlevel 1 goto :eof
echo. ...About to "rmdir /q/s %temp%\*"
goto :eof
:check_ntauth
if not `whoami` == "nt authority\system" goto :not_sys_account
goto :eof
:not_sys_account
echo. &echo. Error: must be run as "nt authority\system" user. &echo.
exit /b 1
echo. As desired, this line is never executed.
与原始代码的区别在于 exit/b 1
现在指定了一个 ERRORLEVEL
并且检查 if errorlevel 1 goto :eof
终止设置了 ERRORLEVEL
时的脚本。
关于windows - 在 "call :loop"中完全停止批处理文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19258020/