批處理指令碼 - 除錯



當您處理大型複雜的批處理指令碼時,除錯批處理指令碼變得非常重要。

以下是您可以用來除錯批處理檔案的方法。

使用 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.. 

將錯誤訊息記錄到另一個檔案

僅檢視命令提示符上顯示的一堆 echo 可能很難除錯錯誤。另一種簡單的方法是將這些訊息記錄到另一個檔案中,然後一步一步地檢視它以瞭解發生了什麼錯誤。

這是一個示例,請考慮以下 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;如果命令失敗,則返回 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 . . .
廣告