如何确保批处理脚本中的每个命令都成功

时间:2018-04-27 21:27:37

标签: batch-file

我在批处理脚本中有一个包含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行返回相同的值。但是,我无法在每个命令后输入IF%ERRORLEVEL%== 0。那么,我怎么能编写脚本来处理这个问题。

2 个答案:

答案 0 :(得分:0)

您应首先将文件另存为.cmd而不是.bat,以便更好地处理错误。也总是用双引号括起你的路径。然后我建议你测试存在以及克服错误级别。

If exist "%Destination%\%NAME3%" rmdir "%Destination%\%NAME3%"

答案 1 :(得分:0)

对于代码示例,我建议如下:

@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
)

此批处理文件几乎可以处理在执行此批处理文件期间可能发生的所有错误。剩下的问题可能是由其值中包含一个或多个双引号的环境变量引起的。解决方案是使用延迟扩展。

Linux shell脚本解释器具有选项-e,如果任何命令或应用程序返回的值不等于0,则立即退出脚本执行。但Windows命令解释程序cmd.exe没有这样的选项。在命令提示符窗口cmd.exe中运行时,可以读取cmd /?的选项。

因此有必要在批处理文件中使用:

  • if exist "..." exit /B 1goto :EOF
  • if not exist "..." exit /B 1goto :EOF
  • if errorlevel 1 exit /B 1goto :EOF
  • ... || exit /B 1... || goto :EOF

另请参阅Stack Overflow文章: