如何获取当前行号?涉及IT技术相关内容。

12

我尝试编写一个通用的批处理文件,可以告诉我错误发生的行号,而无需在代码中编写每个行号,这样有点烦人。
在批处理文件运行时获取当前行号是否可能?
这样以下代码就可以工作了吗?

@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%
)
1个回答

20

总有办法……
我找到的不是完美解决方案,但是可以使用一个很好的解决方式。

我调用一个函数,该函数使用findStr在自己的批处理文件(%~f0)中搜索函数参数<uniqueID>,因此只有当这些<uniqueID>对于整个批处理文件确实是独一无二时,它才能正常工作。从findstr / N的结果中获取行号。

在这个示例中:
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
)

7
+1,嗨,jeb,我刚刚注意到这篇帖子,非常酷 :-) 你可能应该将FINDSTR搜索更改为使用/n /c:" %~2 "(ID两侧有空格),并遵循ID永远不包含空格的约定。您不希望"abc123"与"zabc1234"匹配。 /C选项还可以防止"A.1"被解释为正则表达式。此外,为避免在FINDSTR中出现转义问题,请勿在ID中包含反斜杠,或者在代码中搜索和替换\为\。 - dbenham
为什么不使用%RANDOM%来动态生成唯一ID? - Glenn Slayden
@GlennSlayden 因为 ID 必须硬编码在文件中。Findstr 必须能够找到固定文本。 - jeb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接