Git: Check for conflicts before merge
How can we check if a merge is going to create a conflict or not without actually doing the merge.
Apparently there is no single command for this, but it is easy to do:
git merge --no-commit --no-ff BRANCH-TO-MERGE echo $? git merge --abort
The first command will try to merge, but without committing the change and without fast-forwarding.
This command will succeed if the merge can be executed and it will fail if there is a conflict. So we can check if the exit code $? was 0 (success) of non-zeo (failure). Then we have to clean up the partial merge.
Sequence to demonstrate
examples/check_for_conflict.sh
git init echo 1 > README git add README git commit -m 1 git checkout -b conflict echo "2 in conflict" >> README git add . git commit -m "2 in conflict" git checkout master git checkout -b simple echo 1 > OTHER git add . git commit -m "other" git checkout master echo 2 >> README cat README git add . git commit -m "2 in master" git checkout -b fast echo f > FAST git add . git commit -m "fast" git checkout master git status git merge --no-commit --no-ff fast echo $? git status git merge --abort git status git merge --no-commit --no-ff simple echo $? git status git merge --abort git status git merge --no-commit --no-ff conflict echo $? git status git merge --abort
Published on 2019-06-26