Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / DevOps / Git

Git – Error: Refusing to Merge Unrelated Histories

4.00/5 (1 vote)
14 Aug 2022CPOL2 min read 8K  
We are showing how to overcome Git errors and 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 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 branches have “unrelated histories.” I will show the problem that appeared when I was using GitHub and SourceTree but can happen with other tools and remote repositories.

The problem that I had, that just happened, but I am sure will happen again to me and to other people, was that I during work 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.

Image 1

Ok, there is no need to have two branches here, 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:

Image 2

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

2 Solution

Since our two branches do not have a common ancestor commit, SurceTree thinks we are doing something wrong. But 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 that from SourceTree GUI. So, we need GitBash to run the command line Git commands. Explanation of 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 merge will continue.

Image 3

And here is what merged branches now look like:

Image 4

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)