📌 问题背景
在使用 Git 进行代码推送时,遇到以下错误:
bash
$ git push
To https://github.com/bmjwin-ok/springboot4-demo.git
! [rejected] main -> main (non-fast-forward)
error: failed to push some refs to 'https://github.com/bmjwin-ok/springboot4-demo.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. If you want to integrate the remote changes,
hint: use 'git pull' before pushing again.
问题原因分析
-
远程仓库有新提交 :在 GitHub 上创建仓库时,生成了初始提交(如
README.md) -
本地也有独立提交 :本地
git init后也产生了提交 -
两个提交没有共同历史:导致本地和远程的分支历史不相关
-
Git 拒绝推送:防止覆盖远程的提交
查看提交历史:
bash
$ git log --oneline
0c588ad (HEAD -> main, origin/main) Initial Commit for SpringBoot4 learning.
2d09e6e Initial Commit for SpringBoot4 learning.
目标 :删除远程的 0c588ad 提交,只保留本地的 2d09e6e 提交。
🛠️ 解决方案
方案一:使用 git reset --hard + git push --force
步骤 1:查看提交历史
bash
git log --oneline
确认要保留的提交和要删除的提交。
步骤 2:硬重置到目标提交
bash
git reset --hard 2d09e6e
执行后输出:
text
HEAD is now at 2d09e6e Initial Commit for SpringBoot4 learning.
步骤 3:验证本地状态
bash
git log --oneline
# 应该只剩 2d09e6e 一个提交
步骤 4:强制推送到远程
bash
git push --force origin main
或者使用更安全的 --force-with-lease:
bash
git push --force-with-lease origin main
步骤 5:最终验证
bash
git log --oneline
git ls-remote origin main
# 两者应该指向同一个提交哈希