Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
   ...
like image 743
Simon East Avatar asked Nov 12 '15 00:11

Simon East


People also ask

What is git branch command?

The git branch command lets you create, list, rename, and delete branches. It doesn't let you switch between branches or put a forked history back together again. For this reason, git branch is tightly integrated with the git checkout and git merge commands.


2 Answers

You can determine what branch you are on using the git branch command so we'll use the output of that for our check. The asterisk will mark the current branch, like so:

D:\>git branch
  master
* staging

We can pipe this output to the find command and then to an IF statement:

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

The > NUL just silences the output of the find.
find will trigger an ERRORLEVEL 1 if it cannot find the string anywhere in the output.

like image 133
Simon East Avatar answered Oct 21 '22 08:10

Simon East


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.

like image 4
jbdev Avatar answered Oct 21 '22 07:10

jbdev