DEV Community

Cover image for Git Error: `fatal: refusing to merge unrelated histories`
Werliton Silva
Werliton Silva

Posted on

Git Error: `fatal: refusing to merge unrelated histories`

What does this error mean?

The error fatal: refusing to merge unrelated histories occurs when Git tries to merge two repositories that have no shared commit history. In other words, the repositories were initialized separately and now you're trying to connect them.

Error

Common scenarios:

  • You created a local repo with git init, made some commits, and then connected it to a GitHub remote repo.
  • You started a new Git repo over an existing project.
  • You're trying to merge two completely separate repositories.

How to fix it

Use the --allow-unrelated-histories flag to force Git to merge:

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

Git will open your editor so you can confirm the merge commit.


How to avoid this error

1. Clone first

If you're starting a project from a remote repository, always clone it first:

git clone https://github.com/user/repo.git
cd repo
Enter fullscreen mode Exit fullscreen mode

This way, you start with the full remote history.

2. Avoid git init if you'll connect to a remote

Don't initialize a local Git repo with git init if you plan to use a remote repository. Create the repo on GitHub first and then clone it.

3. Push with force only if needed

If you've already initialized locally and added a remote manually:

git remote add origin https://github.com/user/repo.git
Enter fullscreen mode Exit fullscreen mode

You may choose to force-push your local history:

git push -u origin main --force
Enter fullscreen mode Exit fullscreen mode

⚠️ Warning: this will overwrite the remote history with your local commits.


Conclusion

This Git error is common when setting up new projects. The fix is simple, but the key is understanding why it happens and how to structure your workflow to avoid it. Stick to best practices like cloning before coding, and avoid mixing multiple Git histories.

Have you ever faced this error? How did you solve it?

Top comments (1)

Collapse
 
michael_liang_0208 profile image
Michael Liang

Nice post.