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

Batch file 如何确保批处理脚本中的每个命令都成功,batch-file,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

我有一个批处理文件,在批处理脚本中有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。那么,我该如何编写脚本来处理这个问题。

为了更好地处理错误,您应该首先将文件保存为
.cmd
,而不是
.bat
。另外,请始终使用双引号将路径括起来。然后,我建议您也测试存在性,以克服错误级别

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

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

@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的选项

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

  • 如果存在“…”退出/B 1
    转到:EOF
  • 如果不存在“…”退出/B 1
    转到:EOF
  • 如果错误级别1退出/b1
    转到:EOF
  • <代码>| |退出/b1
。|转到:EOF
另请参见堆栈溢出文章:


显示一个示例,而不是检查是否存在,使用
md%Destination%\%NAME%2>Nul
来抑制错误。否则,在失败时与
|
一起使用,在成功时与
&&
一起使用。在第4行中,路径没有双引号,如果
%Destination%
中有空格,则可能会失败。我希望这些行失败。但是,我希望在脚本的末尾显示每一行和函数的返回代码。如果希望第4行和第6行的错误级别为1,为什么不对这两行使用
If%errorlevel%==1
,对其他行使用
If%errorlevel%==0