hakre
hakre

Reputation: 198204

How to detect a merge conflict in a Git repository work tree (non-bare)

Is there a simple git command that can tell (e.g. by exit status) whether a work tree has unmerged paths / a merge conflict? Like when a git merge operation fails and git returns to the shell and git status shows that there are merge conflicts.

I found so far git status and a list of values it would output in an unmerged situation (the XY status codes then):

X          Y     Meaning
-------------------------------------------------
D           D    unmerged, both deleted
A           U    unmerged, added by us
U           D    unmerged, deleted by them
U           A    unmerged, added by them
D           U    unmerged, deleted by us
A           A    unmerged, both added
U           U    unmerged, both modified
-------------------------------------------------

So that the only way to detect so for me so far would be to match against a list of XY codes that represent unmerged, e.g.:

AA | DD | [ADU]U | U[AD]

(added horizontal white space for readability)

A check with zero exit status in case of unmerged paths (or non-zero if none) then would be (if my understanding of git status is correct here):

git status --porcelain -z \
  | grep -q -z '^\(AA\|DD\|[ADU]U\|U[AD]\) '

This becomes rather convoluted and I'm looking for a more simple command (best with git only).

I want to use it in bash script for a local build that rejects further processing if there are any unmerged paths in the git repositories work tree.

Upvotes: 3

Views: 626

Answers (1)

Piotr Wittchen
Piotr Wittchen

Reputation: 3922

There's already answer to that question here: https://stackoverflow.com/a/501461/1150795.

Provide --no-commit flag during the merge as follows:

git merge --no-commit --no-ff $BRANCH

Then examine staged changes:

git diff --cached

To undo merge, type:

git merge --abort

Alternatively you can compare your local branch against the remote branch if that's your case:

git fetch origin/master
git diff master origin/master

Upvotes: 0

Related Questions