How to ask git if the repository is in a conflict stage? How to ask git if the repository is in a conflict stage? git git

How to ask git if the repository is in a conflict stage?


Using git status or similar will be slow on a large repository, as it needs to check the entire working copy's status, as well as the index. We're only interested in the index, so we can use much quicker commands that will just check the index state.

Specifically, we can use git ls-files --unmerged. That command will produce no output if there are no files in a conflicted state, and something like the below if there are:

$ git ls-files --unmerged100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 1       filename100644 4a58007052a65fbc2fc3f910f2855f45a4058e74 2       filename100644 65b2df87f7df3aeedef04be96703e55ac19c2cfb 3       filename

So we can just check if that file produces any output: [[ -z $(git ls-files --unmerged) ]]. That command will give a return code of zero if the repository is clean, and non-zero if the repository has conflicts. Replace -z with -n for the inverse behaviour.

You could add the following to your ~/.gitconfig:

[alias]    conflicts = ![[ -n $(git ls-files --unmerged) ]]    list-conflicts = "!cd ${GIT_PREFIX:-.}; git ls-files --unmerged | cut -f2 | sort -u"

This will give behaviour like the following:

$ git st# On branch masternothing to commit (working directory clean)$ git conflicts && echo 'Conflicts exist' || echo 'No conflicts'No conflicts$ git merge other-branchAuto-merging fileCONFLICT (content): Merge conflict in fileAutomatic merge failed; fix conflicts and then commit the result.$ git conflicts && echo 'Conflicts exist' || echo 'No conflicts'Conflicts exist$ git list-conflictsfile

(The cd ${GIT_PREFIX:-.} part of the second alias means you only get a list of the conflicting files in the current directory, not for the entire repository.)


On GNU/anything I'd do

$ if { git status --porcelain | sed -nr '/^U.|.U|AA|DD/q1'; }> then # no merge conflicts> else # merge conflicts> fi


Would this work for you?

$ git merge origin/masterAuto-merging fileCONFLICT (content): Merge conflict in fileAutomatic merge failed; fix conflicts and then commit the result.$ git status# On branch master# Your branch and 'origin/master' have diverged,# and have 1 and 1 different commit each, respectively.## Unmerged paths:#   (use "git add/rm <file>..." as appropriate to mark resolution)##       both modified:      file#no changes added to commit (use "git add" and/or "git commit -a")$ git status -s         UU file

You can tell you are in a merge state because it tells you that a file has 2 modifications and both are unmerged. Actually, if you have XY file where X and Y are both letters, you probably have a conflict that needs resolving.