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
...
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
...
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.
git branch --show-current
will provide the same result as git rev-parse --abbrev-ref HEAD
β
Reverential 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.
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.
git branch --show-current
will provide the same result as git rev-parse --abbrev-ref HEAD
β
Reverential © 2022 - 2024 β McMap. All rights reserved.