Resolving Merge Conflicts

Expected level: Working

A merge conflict happens when Git cannot combine two changes automatically, usually because both branches changed the same lines. You resolve it by deciding what the final text should be.

How conflicts occur

Git merges changes line by line. When two branches changed the same lines differently, or one branch deleted a file the other edited, Git stops and asks you to decide. It writes both versions into the file with markers:

<<<<<<< HEAD
the version on your current branch
=======
the version from the branch being merged
>>>>>>> feature/login

During a rebase the two sides are reversed: the top part is the branch you are rebasing onto, and the bottom part is your own commit.

Resolving a conflict

  1. Run git status. Conflicted files are listed as “both modified”.
  2. Open each file and decide what the code should be: one side, the other, or a combination. Remove the markers.
  3. Build and run the tests. A conflict-free merge can still be wrong.
  4. Stage the file with git add <file>.
  5. Finish with git commit (or git merge --continue, or git rebase --continue if you were rebasing).

To back out and start over, run git merge --abort (or git rebase --abort).

Tips

  • Understand both changes before you choose. If you are unsure what the other side intended, ask the author.
  • Your IDE or git mergetool can show the two versions side by side.
  • Never accept “all mine” or “all theirs” just to make the conflict go away.
  • Small branches that are merged often produce fewer and smaller conflicts.

Try it

In a test repository, change the same line of a file on two branches, then merge one into the other. Resolve the conflict, run git log --graph --oneline, and look at the merge commit.

Common mistakes

  • Leaving conflict markers in the file and committing them.
  • Taking all of one side just to make the conflict go away.
  • Skipping the build and tests after resolving.

Check yourself

  • What do the lines between <<<<<<< and ======= show?
  • How do you back out of a conflicted merge?

Related topics

Terms

Further reading