Git 实战:解决 “non-fast-forward“ 推送失败 + 删除远程错误提交
问题背景在使用 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 --hardgit push --force步骤 1查看提交历史bashgit log --oneline确认要保留的提交和要删除的提交。步骤 2硬重置到目标提交bashgit reset --hard 2d09e6e执行后输出textHEAD is now at 2d09e6e Initial Commit for SpringBoot4 learning.步骤 3验证本地状态bashgit log --oneline # 应该只剩 2d09e6e 一个提交步骤 4强制推送到远程bashgit push --force origin main或者使用更安全的--force-with-leasebashgit push --force-with-lease origin main步骤 5最终验证bashgit log --oneline git ls-remote origin main # 两者应该指向同一个提交哈希