如何获取当前行号?

jeb*_*jeb 8 cmd batch-file

我正在尝试构建一个通用批处理文件,该文件可以使用行号来判断错误,其中出现错误.
但是在代码中编写每个行号有点烦人.

当批处理文件正在运行时,是否可以获取当前行号?
以便以下代码可以工作?

@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%
)
Run Code Online (Sandbox Code Playgroud)

jeb*_*jeb 18

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

我把它搜索自己的批处理文件(功能%~f0与FINDSTR),该函数的参数<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
)
Run Code Online (Sandbox Code Playgroud)

  • +1,嗨jeb,我刚注意到这篇文章,非常酷:-)你可能应该改变你的FINDSTR搜索使用`/ n/c:"%~2"`(ID的两边的空格)与一个约定ID永远不会包含空格.你不希望"abc123"匹配"zabc1234"./ C选项还可以防止像"A.1"这样的东西被解释为正则表达式.此外,ID不应包含反斜杠以避免FINDSTR出现转义问题,或者在代码中搜索并替换\ with \\. (6认同)