[Trouble Shooting] error “fatal: refusing to merge unrelated histories” in Git

Problem

When I tried to pull from remote repository, the error “fatal: refusing to merge unrelated histories” occurred. How can I solve it?

$ git pull origin main
warning: no common commits
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
From https://github.com/s-nako/ColorSelector
 * branch            main       -> FETCH_HEAD
 * [new branch]      main       -> origin/main
fatal: refusing to merge unrelated histories

Cause

This error occurs because “pull” command is targeted for 2 branches that has same root. In my case, remote main was generated on GItHub and local main was generated in local directory by “git init”.

Solution

Use “–allow-unrelated-histories” option for pull command as below.

$ git pull origin main --allow-unrelated-histories
From https://github.com/s-nako/ColorSelector
 * branch            main       -> FETCH_HEAD
Merge made by the 'recursive' strategy.
 README.md | 2 ++
 1 file changed, 2 insertions(+)
 create mode 100644 README.md