Resolving Merge Conflicts in Git

Today we will look at how to resolve a merge conflict if one should happen to arise when merging two branches.

Example Git History

Suppose we have a Git version history of a single file called 99_bottles.txt that looks like this:

Here are the contents of the two different versions of 99_bottles.txt:

On most recent master commit:

99 bottles of beer on the wall, 99 bottles of beer.
Take one down, pass it around, 98 bottles of beer on the wall...

On most recent alternate commit:

99 bottles of beer on the wall, 99 bottles of beer.
If one of those bottles should happen to fall, 98 bottles of beer on the wall...

Merging alternate into master

Assuming we’re checked out to the master branch

$ git branch
alternate
* master

We can attempt to merge alternate into our currently checked out branch, master, by using the git merge <branch-name> command.

$ git merge alternate
CONFLICT (content): Merge conflict in 99_bottles.txt
Automatic merge failed; fix conflicts and then commit the result.

As indicated by the terminal output, the merge failed because there was a merge conflict.

Resolving a Merge Conflict

Opening 99_bottles.txt reveals the result of the merge conflict that we must resolve before trying to merge again.

99 bottles of beer on the wall, 99 bottles of beer.
<<<<<< HEAD
Take one down, pass it around, 98 bottles of beer on the wall...
======
If one of those bottles should happen to fall, 98 bottles of beer on the wall...
>>>>>> alternate

Now suppose that we wanted to keep the changes of the branch that was merged in, then we can remove the conflicted change associated with HEAD and keep the change associated with alternate to result in the following file:

99 bottles of beer on the wall, 99 bottles of beer.
If one of those bottles should happen to fall, 98 bottles of beer on the wall...

Next step is to stage the file and commit:

$ git add 99_bottles.txt
$ git commit -m "Merge alternate into master."

Our second merge attempt should have been successful and resulted in the following Git history:

Written by

Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store