Git - Error - Refusing To Merge Unrelated Histories

Your Git tool might sometimes refuse to merge branches, with the error: “fatal: refusing to merge unrelated histories”. We are showing how to overcome the problem.

1 Problem

Sometimes during work with GitHub, you will get into a situation where you have created initial branches on both sides, local and remote. Naturally, you would like to merge the branches, but your Git tool might refuse to merge them because the branches have “unrelated histories." I will show the problem that appeared when I was using GitHub and SourceTree but that can happen with other tools and remote repositories, as well.

The problem that I had, but I am sure will happen again to me and to other people, was that during work I finished with two initial branches created: main and master. The “main” branch is by default created by GitHub, and there is a readme file there. The branch “master” is created by default by SourceTree, and my code is in it.

Ok, there is no need to have two branches here, so let’s merge them and get rid of one of them. Let’s keep GitHub default branch “main” and delete “master."

But there is a problem when you try to merge those two branches:

It gives an error: “fatal: refusing to merge unrelated histories

2 Solution

Since our two branches do not have a common ancestor commit, SourceTree thinks that we are doing something wrong. However, we know we are right and want to force it.

2.1. Forcing merge

I looked and it says in [1] that you cannot resolve this from SourceTree GUI. So, we need GitBash to run the command line Git commands. An explanation of the problem and instructions are at [2].
We need to run “git merge <branch-name> --allow-unrelated-histories."

So, you can open GitBash from SourceTree (Terminal button), and execute the command. You will be prompted to enter a commit comment in the separate text editor. Then the merge will continue.

Here is what the merged branches now look like:

3 References


Similar Articles