报错急救:Git
git push被拒绝(rejected / non-fast-forward / fetch first)怎么办
远程仓库有你本地没有的新内容,Git不让你直接覆盖。先拉取合并再推送,别急着force。
你的终端里是不是这样报错原文
1To github.com:yourname/my-app.git
2 ! [rejected] main -> main (fetch first)
3error: failed to push some refs to 'github.com:yourname/my-app.git'
4hint: Updates were rejected because the remote contains work that you do not
5hint: have locally. This is usually caused by another repository pushing to
6hint: the same ref. If you want to integrate the remote changes, use
7hint: 'git pull' before pushing again.
8hint: See the 'Note about fast-forwards' in 'git push --help' for details.
人话:这是怎么回事
push是把本地提交送到GitHub。被拒绝说明:远程仓库里有你本地没有的提交(可能是你在网页上改过文件、在另一台电脑推过,或者建仓库时勾选了自动生成README)。
Git不允许你直接盖过去,怕把别人的内容弄丢。它是在保护你,不是出故障了。解法是先把远程的内容合并进来,再推送。
最快的解法:把这段发给AI
复制给AIClaude Code
1我执行
git push被拒绝了,报错里有"Updates were rejected"和"fetch first"(或non-fast-forward)。2
3请按这个顺序处理,并且每一步先告诉我在做什么:
41. 运行
git status、git log --oneline -5、git remote -v,确认现状。52. 运行
git fetch,对比git log --oneline origin/main..HEAD和HEAD..origin/main,告诉我本地和远程各多了哪些提交。63. 用
git pull --rebase合并远程的新内容。如果出现冲突,停下来解释冲突在哪,不要擅自选择保留哪一边。74. 再
git push。8严禁使用
git push --force。完成后用git status和git log验证本地与远程一致。想自己动手的话
终端
$ git pull --rebase
先把远程的新提交拿下来,再把你的提交接在后面。如果提示冲突,看git-merge-conflict。
终端
$ git push
合并完成后再推送,通常就通过了。
如果报错是fatal: refusing to merge unrelated histories,说明本地和远程是两个各自独立开始的项目(典型情况:本地先git init,GitHub上又新建了带README的仓库)。确认远程内容可以合并后:
终端
$ git pull origin main --allow-unrelated-histories
这条命令允许把两段互不相关的历史拼在一起。
下次怎么避免
开工前先git pull。一个人用多台电脑时,换机器前先推送、到新机器先拉取。在GitHub网页上直接改文件也会造成这个情况,改完记得本地同步。
还不行?
如果报错变成了「Authentication failed」,看github-password-auth。如果连不上GitHub,看github-connect-timeout。
发现过时或写错的地方,欢迎在 GitHub 告诉我们。