'Git : Determine if branch is in a merge conflict state
I am writing a bash script to do some automation. Part of the script involves navigating to a local repo, switching to the local master branch, then pulling the remote master to update the local master branch with the latest code.
Does anyone know if there's a way I can programatically determine if the pull resulted in a merge conflict so that I can bail at that point and not execute the rest of the script?
Any help / info is appreciated, thanks!
Solution 1:[1]
Use git ls-files -u. It prints unmerged files. If it prints nothing, there are no unmerged files.
However, while that's a direct answer for the question you asked "as asked", using git pull in a script is a bit dicey: pull is a convenience script that runs fetch for you, and then (depending on how you direct it and/or have configured your repo) runs either merge or rebase for you. Given that you are writing a script that has a particular goal in mind, you should most likely be using lower-level commands that do more-specific things. For instance, you might use git fetch followed by (as Etan Reisner suggested in a comment) git merge --ff-only so as to never attempt a merge.
Solution 2:[2]
Based on the answer given by torek, here is a ready-to-use snippet:
CONFLICTS=$(git ls-files -u | wc -l)
if [ "$CONFLICTS" -gt 0 ] ; then
echo "There is a merge conflict. Aborting"
git merge --abort
exit 1
fi
Solution 3:[3]
This lists files with a merge conflict:
git diff --name-only --diff-filter=U
Solution 4:[4]
git config --global user.email "Email Id" && git config --global user.name "User Name" && git merge --no-commit --no-ff origin/master && git diff --cached && git merge --abort
This code is combination of multiple steps.
- Starting a merge with no-commit and no-ff.
- Fetching differences in both branch.
- Aborting the merge
When there will be any conflict it will fail at second step and you will get merge conflict error as output , else you will get difference in both branch.
For details you can go to GIT-SCM documentation
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | torek |
| Solution 2 | flix |
| Solution 3 | Michael Schmid |
| Solution 4 | Aniket Kumar |
