Search code examples
gitbatch-fileerrorlevel

How to verify the current git branch in a Windows BAT file


I'm trying to figure out how to verify that the user is on the correct branch before running some commands in my BAT file.

What's the best way to perform this kind of check...

IF (on "master" git branch) THEN
   ...
ELSE
   ...

Solution

  • Use the following to return only the current branch:

    git rev-parse --abbrev-ref HEAD
    

    FINDSTR can use a regular expression to match on the branch name:

    FINDSTR /r /c:"^master$" 
    

    This works except that git rev-parse uses LF instead of CRLF for line endings, while the end of line match in the regex is looking for CR. Adding FIND /v "" to change the LF to CRLF results in this:

    git rev-parse --abbrev-ref HEAD | find /v "" | findstr /r /c:"^master$" > NUL & IF ERRORLEVEL 1 (
      ECHO I am NOT on master
    ) ELSE (
      ECHO I am on master
    )
    

    This will match the branch "master", but not a branch name containing the word master.