DEV Community

OneLineDev
OneLineDev

Posted on

Fix: 'fatal: refusing to merge unrelated histories' in Git

The Error

You run git pull or git merge and see:

fatal: refusing to merge unrelated histories
Enter fullscreen mode Exit fullscreen mode

Why It Happens

Git refuses to merge branches that do not share a common ancestor commit. This typically happens when you created a local repo with git init, created a remote repository on GitHub with a default README.md or .gitignore, and then tried to connect them.


The Quick Fix (One-Liner)

Force Git to merge the two independent project histories:

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

(Note: Replace main with master if your default branch is named master)

If you are merging directly:

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

Resolving the Merge & Pushing

  1. If an editor opens for a commit message:

    • Vim: Type :wq and hit Enter.
    • Nano: Press Ctrl + O, Enter, then Ctrl + X.
  2. If merge conflicts occur:
    Open the conflicting files (e.g., README.md), choose which lines to keep, save, and run:

   git add .
   git commit -m "chore: merge unrelated histories"
Enter fullscreen mode Exit fullscreen mode
  1. Push to Remote:
   git push -u origin main
Enter fullscreen mode Exit fullscreen mode

Alternative: Overwrite Local with Remote

If your local commits don't matter and you just want the remote repository's exact state:

git fetch origin
git reset --hard origin/main
Enter fullscreen mode Exit fullscreen mode

Warning: reset --hard permanently discards uncommitted local changes.

Top comments (0)