Git: How to Handle Merge Conflicts

Git Tips & Commands

When you merge two branches (or merge a local and remote branch) you can sometimes get a conflict. For example, you and another developer unknowingly both work on the same part of a file. The other developer pushes their changes to the remote repo. When you then pull them to your local repo you'll get a merge conflict. Luckily Git has a way to handle conflicts, so you can see both sets of changes and decide which you want to keep.

What To Do With a Merge Conflict

1. When you get a merge conflict, take note of the file(s) that have a conflict.
2. In your code editor, open a conflicted file and look for these conflict markers:

<<<<<<< HEAD
Marks the start of the changes.

=======
Divides your changes from the changes in the other branch.

>>>>>>> branch-name
Marks the end of the changes.

3. Now you must decide how to resolve the conflict:

  • You can edit the code, deciding which version you want to keep, or edit to make it something new (such as a combination of the two). Make whatever edits you need to, and be sure to delete the conflict markers.
  • Instead of editing the code, you may know which changes you want to keep (ours or theirs). For example you may be working on a feature branch as others work on the master branch. When you go to merge your feature branch into master you may get a conflict. Here's how to use one of those versions:
  • git checkout --ours example.html (You are on the master branch trying to merge in the feature branch, so --ours will use the version from the current master branch)
  • git checkout --theirs example.html (You are on the master branch trying to merge in the feature branch, so --theirs will use the version from the feature branch you're merging into master)
  • If you get confused between ours and theirs, run one command and look at the file. Then run the other and look again to see which version you want to keep. These commands can be very useful because you don't have to edit files, remove conflict markers, etc. The files become the version you want.

4. Now you can stage and commit your changes (and push if needed).

Go Beyond Git

We offer a full suite of coding courses for students of all levels. Learn through real-world projects from expert instructors. Check out our coding bootcamps and classes now:

How to Learn Git

Master Git with hands-on training. Git is a free, open-source version control system that allows developers to track the changes they make to code.

Yelp Facebook LinkedIn YouTube Twitter Instagram