2011-01-05 111 views
6

我想建立一個通用的批處理文件,可以告訴錯誤的行號,錯誤發生在哪裏。
但是在代碼中寫入每行號碼有點煩人。如何獲取當前行號?

批處理文件運行時,是否可以獲取當前行號?
以便下面的代碼可以工作?

@echo off 
call :doSomething 1 

if %errorlevel% GTR 0 (
    REM Do something magic, to retrieve the lineNo 
    call :getCurrentLineNo currentLineNo 
    echo Error near %currentLineNo% 
) 

call :doSomething 2 

if %errorlevel% GTR 0 (
    call :getCurrentLineNo currentLineNo 
    echo Error near %currentLineNo% 
) 

回答

16

總是有辦法...
我發現不完美的解決方案,但一個好的解決辦法,我可以使用。

我調用一個函數,它用findStr搜索自己的批處理文件(%~f0),函數參數爲<uniqueID>,所以只有在這些<uniqueID>對於整批來說真的是唯一的。
findstr /N的結果獲得的linenumber。

在此示例中:
6: call :getLineNumber errLine uniqueID4711 -2

第三個參數-2用於添加偏移到行號,因此結果將是4

@echo off 
SETLOCAL EnableDelayedExpansion 

dir ... > nul 2> nul 
if %errorlevel% NEQ 0 (
    call :getLineNumber errLine uniqueID4711 -2 
    echo ERROR: in line !errLine! 
) 

set /a n=0xGH 2> nul 
if %errorlevel% NEQ 0 (
    call :getLineNumber errLine uniqueID4712 -2 
    echo ERROR: in line !errLine! 
) 
goto :eof 

::::::::::::::::::::::::::::::::::::::::::::: 
:GetLineNumber <resultVar> <uniqueID> [LineOffset] 
:: Detects the line number of the caller, the uniqueID have to be unique in the batch file 
:: The lineno is return in the variable <resultVar> add with the [LineOffset] 
SETLOCAL 
for /F " usebackq tokens=1 delims=:" %%L IN (`findstr /N "%~2" "%~f0"`) DO set /a lineNr=%~3 + %%L 
( 
    ENDLOCAL 
    set "%~1=%LineNr%" 
    goto :eof 
) 
+4

+1,喜傑布,我只注意到這個崗位,非常酷的:-)你或許應該改變你的FINDSTR搜索使用'/ N/C:在兩側的 「%〜2」'(空間ID)以及ID從不包含空格的約定。你不希望「abc123」匹配「zabc1234」。/C選項還可以防止像「A.1」這樣的東西被解釋爲正則表達式。此外,ID不應該包含反斜槓以避免FINDSTR出現轉義問題,否則請用代碼中的\\搜索並替換\。 – dbenham 2012-08-09 19:59:49