批处理脚本 - 调试

当您处理大型复杂批处理脚本时,调试批处理脚本变得非常重要。

以下是调试批处理文件的方法。

使用 echo 命令

一个非常简单的调试选项是尽可能在批处理脚本中使用 echo 命令。 它将在命令提示符中显示消息并帮助您调试出现问题的地方。

这是一个简单的示例,根据给定的输入显示偶数。 echo 命令用于显示结果以及未给出输入的情况。 同样,当您认为可能发生错误时,可以在适当的地方使用 echo 命令。 例如,如果给定的输入是负数、小于2等。

示例

@echo off  
if [%1] == [] ( 
   echo input value not provided 
   goto stop 
)  
rem Display numbers 
for /l %%n in (2,2,%1) do ( 
   echo %%n 
)  
:stop 
pause 

输出

C:\>test.bat 
10 
2 
4 
6 
8 
10 
22
Press any key to continue ... 

使用 pause 暂停命令

另一种方法是在出现错误时暂停批处理执行。 当脚本暂停时,开发人员可以修复问题并重新启动处理。

在下面的示例中,批处理脚本已暂停,因为输入值是强制性的且未提供。

示例

@echo off  
if [%1] == [] ( 
   echo input value not provided 
   goto stop 
) else ( 
   echo "Valid value"     
)  
:stop 
pause 

输出

C:\>test.bat 
 input value not provided 
Press any key to continue.. 

将错误消息记录到另一个文件

仅仅查看命令提示符上显示的一堆回显可能很难调试错误。 另一个简单的方法是将这些消息记录在另一个文件中,并逐步查看它以了解出了什么问题。

这是一个示例,请考虑以下 test.bat 文件:

net statistics /Server 

.bat 文件中给出的命令是错误的。 让我们记录消息并看看我们得到了什么。

在命令行中执行以下命令:

C:\>test.bat > testlog.txt 2> testerrors.txt

文件 testerrors.txt 将显示错误消息,如下所示:

The option /SERVER is unknown.  
The syntax of this command is:  
NET STATISTICS 
[WORKSTATION | SERVER]  
More help is available by typing NET HELPMSG 3506.

查看上述文件,开发人员可以修复程序并再次执行。

使用 ErrorLevel 检测错误并记录它们

如果命令执行成功,Errorlevel 返回 0;如果失败,则 Errorlevel 返回 1。

考虑以下示例:

@echo off 
PING google.com  
if errorlevel 1 GOTO stop  
:stop 
   echo Unable to connect to google.com 
pause

在执行过程中,您可以看到错误以及日志:

C:\>test.bat > testlog.txt

testlog.txt

Pinging google.com [172.217.26.238] with 32 bytes of data: 
Reply from 172.217.26.238: bytes=32 time=160ms TTL=111 
Reply from 172.217.26.238: bytes=32 time=82ms TTL=111 
Reply from 172.217.26.238: bytes=32 time=121ms TTL=111 
Reply from 172.217.26.238: bytes=32 time=108ms TTL=111  
Ping statistics for 172.217.26.238: 
   Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), 
Approximate round trip times in milli-seconds: 
   Minimum = 82ms, Maximum = 160ms, Average = 117ms
   Connected successfully 
Press any key to continue . . .

如果失败,您将在 testlog.txt 中看到以下日志。

Ping request could not find host google.com. Please check the name and try again. 
Unable to connect to google.com 
Press any key to continue . . .