尝试从 Windows 批处理文件访问当前 git 分支并将其放入变量中

尝试从 Windows 批处理文件访问当前 git 分支并将其放入变量中

我正在尝试将当前 git 分支名称放入 Windows 批处理文件中的变量中。为此,我尝试对“git branch”命令的输出中的每个分支进行 for 循环并搜索“*”。我认为我的实现中有一些细节阻碍了我成功,也许是 for 循环内部的细节?我下面有两个批处理文件,一个尝试使用,findstr另一个使用第一个字符的字符串比较。没有触发 if 语句,我认为它要么是变量赋值,要么是字符串比较的语法。

批处理文件 1(字符串比较)


SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
SET variable="foobar"
SET currentBranch
FOR /F "tokens=* USEBACKQ" %%F IN (`git branch`) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
  SET variable=%%F

  SET result=%variable:~0,2%

IF "%result%"=="* "  (
  ECHO found current branch 
  SET currentBranch=%%F
) ELSE (
    ECHO Not current branch
)

)
ECHO END
ECHO currentbranch=%currentBranch%
ECHO variable=%variable% 
ECHO result=%result%


ENDLOCAL
pause

批处理文件 2 (findstr)

git branch | find "* master"| findstr /B *  > NUL & IF ERRORLEVEL 1 (
    ECHO I am NOT on master
) ELSE (
    ECHO I am on master
)


SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
SET variable="foobar"
SET currentBranch
FOR /F "tokens=* USEBACKQ" %%F IN (`git branch`) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
  SET varz=%%F


%%varz|find "* " > NUL & IF ERRORLEVEL 1 (
    ECHO I am NOT on currentBranch
) ELSE (
    ECHO I am on current branch
    SET currentBranch=%%F
)

)
ECHO END
ECHO currentbranch=%currentBranch%
ECHO variable=%variable% 
ECHO result=%result%


ENDLOCAL
pause

答案1

您不需要整个程序来完成此操作。

 @echo off
 set current_branch=
 for /F "delims=" %%n in ('git branch --show-current') do set "current_branch=%%n"
 if "%current_branch%"=="" echo Not a git branch! && goto :EOF
 echo The current branch is %current_branch%

归根结底git branch --show-current,您不需要解析结果。

答案2

以下是对上面错误批次的更正,我认为核心问题是没有使用 !variable! 语法进行动态扩展:

SET count=1
SET variable="bullshit"
SET result="bullshit"
SET currentBranch
FOR /F "tokens=* USEBACKQ" %%F IN (`git branch`) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
  SET variable=%%F

  SET result=!variable:~0,2!

IF "!result!"=="* "  (
  ECHO found current branch 
  SET currentBranch=%%F
) ELSE (
    ECHO Not current branch
)

)

SET currentBranch=!currentBranch:~2!

set Branch=!currentBranch!

相关内容