DEV Community

Umesh Sharma
Umesh Sharma

Posted on

Solving the Error - "fatal: refusing to merge unrelated histories"

This is an error that I encountered while I was trying to merge the two branches main and master.
So what happened, and why did this message appear, and how did I resolve the issue?

Let's understand what happened-

I created a repository on GitHub with a README.md file for my project. And in my local machine, I created a project which was independent of my GitHub repository, and started committing to that independent repository locally.

After adding all the commits to my local repository, I wanted to push the code to the repo on GitHub, which had the README.md file. I added the remote repo by using the command,

git remote add <remote-name> <remote-url>
Enter fullscreen mode Exit fullscreen mode

Now, in order to push the commit, I had to pull the GitHub repo (that I created earlier), which had the README.md file in it, using the command,

git pull origin main

After pulling the file, I had to make that ultimate push to the repo, where I encountered the Error

fatal: unrelated histories error

In simple words, what I did was I initialized a local repository, made some commits to it, and later added a remote that already contained different commits.

Why did this Error occur? let's understand it -

This Error occurred when I tried to merge two repositories( local and remote) that do not share any common history. It likely occurred while interacting with the remote repo when I tried to git pull, git push, and even git merge.
Git was not able to find the shared base to apply and combine changes. So, it refused to merge by default as a safety measure, by throwing an Error.

So Lastly, How did I fix the Error

As I really wanted to combine these repositories, I used a git command to allow the merge with a git option --allow-unrelated-histories

git merge origin main --allow-unrelated-histories
Enter fullscreen mode Exit fullscreen mode

and resolved the merge conflicts that came my way. While running the above command, you will be redirected to the Vim editor. Don't worry if you don't understand it, just follow the brief guide below, and you will be good to go.

Navigating Vim Guide

After saving and exiting the Vim, you just have to push the commit to the branch
git push origin main

Note: Only use this flag if you are certain that the repositories or branches are meant to be combined, as merging unrelated histories can lead to a complicated commit graph if not handled carefully.

A small tip if you are working with a team:
Always verify with your team or repository owner before merging unrelated histories to avoid unintentional conflicts or messy project history.

With that, we can solve this error. Hope this helps you.

Top comments (0)