我有一个批处理文件,在批处理脚本中有10行和5个函数。如何确保批处理文件中的所有命令都成功。
换句话说,计算脚本末尾每个命令返回代码的逻辑是什么。
1. @ECHO OFF
2. if not exist "%Destination%\%NAME%" md %Destination%\%NAME%
3. if not exist "%Destination%\%NAME2%" md %Destination%\%NAME2%
4. rmdir %Destination%\%NAME3%
5. if not exist "%Destination%\NAME4%" md %Destination%\%NAME4%
6. cd /d X:\test1
在上述5行中,第4行返回%ERRORLEVEL% 1,第6行返回相同的%ERRORLEVEL%1。但是,我不能在每个命令之后都加上IF %ERRORLEVEL%==0。那么,我该如何编写脚本来处理这个问题呢。
发布于 2018-04-28 15:21:06
您应该首先将文件保存为.cmd
,而不是.bat
,以便更好地处理错误。此外,请始终使用双引号将路径括起来。然后,我建议你也测试存在,以克服错误级别。
If exist "%Destination%\%NAME3%" rmdir "%Destination%\%NAME3%"
发布于 2018-04-28 22:19:25
对于代码示例,我建议使用以下代码:
@echo off
rem Verify the existence of all used environment variables.
for %%I in (Destination NAME NAME2 NAME3 NAME4) do (
if not defined %%I (
echo Error detected by %~f0:
echo/
echo Environment variable name %%I is not defined.
echo/
exit /B 4
)
)
rem Verify the existence of all used directories by creating them
rem independent on existing already or not and next verifying if
rem the directory really exists finally.
for %%I in ("%Destination%\%NAME%" "%Destination%\%NAME2%") do (
md %%I 2>nul
if not exist "%%~I\" (
echo Error detected by %~f0:
echo/
echo Directory %%I
echo does not exist and could not be created.
echo/
exit /B 3
)
)
rem Remove directories independent on their existence and verify
rem if the directories really do not exist anymore finally.
for %%I in ("%Destination%\%NAME3%") do (
rd /Q /S %%I 2>nul
if exist "%%~I\" (
echo Error detected by %~f0:
echo/
echo Directory %%I
echo still exists and could not be removed.
echo/
exit /B 2
)
)
cd /D X:\test1 2>nul
if /I not "%CD%" == "X:\test1" (
echo Error detected by %~f0:
echo/
echo Failed to set "X:\test1" as current directory.
echo/
exit /B 1
)
此批处理文件处理在执行此批处理文件期间可能发生的几乎所有错误。剩余的问题可能是由于环境变量的值中包含一个或多个双引号引起的。解决方案是使用延迟扩展。
如果任何命令或应用程序返回的值不等于0
,则Linux shell脚本解释器可以选择-e
来立即退出脚本的执行。但是Windows命令解释程序cmd.exe
没有这样的选项。在命令提示符窗口cmd /?
中运行时,可以读取cmd.exe
的选项。
因此,有必要在批处理文件中使用:
if exist "..." exit /B 1
、goto :EOF
if not exist "..." exit /B 1
、goto :EOF
if errorlevel 1 exit /B 1
、goto :EOF
|| exit /B 1
或... || goto :EOF
另请参阅Stack Overflow文章:
https://stackoverflow.com/questions/50070526
复制相似问题