添加Git远程仓库后执行pull报错:拒绝合并无关历史及后续问题
Hey there, let’s break down how to resolve these two git issues you’re facing, step by step:
First, let’s understand the initial error: fatal: refusing to merge unrelated histories
This happens because your local repo and the remote GitHub repo have no shared commit history—they’re essentially two separate repos that Git won’t merge by default (it’s a safety measure to avoid accidental messes). Your idea to use --allow-unrelated-histories was on the right track, but you hit a second snag because you have uncommitted local changes.
Now, fixing the second error: error: Your local changes to the following files would be overwritten by merge
Git blocks the merge here because pulling the remote changes would overwrite the uncommitted work in your local workspace. You’ve got three solid options depending on what you want to do with your local changes:
Option 1: Stash your local changes (best for temporary storage)
If you want to merge the remote code first and come back to your local work later, stash is perfect:
- Stash your current changes:
git stash - Now run the pull with unrelated history allowed:
git pull origin master --allow-unrelated-histories - Once done, restore your stashed changes (you might need to resolve conflicts if there’s overlap):
After resolving any conflicts, commit your changes as usual.git stash pop
Option 2: Commit your local changes first
If your local work is ready to be saved, commit it before merging:
- Stage all your changes:
git add . - Commit the changes with a descriptive message:
git commit -m "Save local work before merging remote master" - Now pull and merge the remote repo:
If conflicts pop up, resolve them in your files, stage the fixes, and commit again.git pull origin master --allow-unrelated-histories
Option 3: Discard local changes (use with caution!)
If you don’t need your uncommitted local work at all, you can reset your repo and pull fresh:
- Reset your local repo to the last committed state (this deletes uncommitted changes permanently):
git reset --hard HEAD - Pull the remote repo with unrelated history allowed:
git pull origin master --allow-unrelated-histories
After merging: Sync your local repo to remote
Once everything is merged smoothly, push your local changes to GitHub to keep both repos in sync:
git push origin master
内容的提问来源于stack exchange,提问作者ramab01

