2011-01-05 114 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