如何使用git revert回退到指定提交且保留Git提交历史?
Hey there! Let's get your git revert issue sorted out properly—you're on the right track choosing git revert instead of git reset --hard, since you need to keep those "added C3" and "added B2" commits in your log. The problem probably comes from using git revert on the wrong target commit. Let me break this down step by step.
先搞懂Git Revert的正确用法
git revert doesn't "jump back" to an old commit—it creates a new commit that undoes the changes from a specific commit. So when you ran git revert 6e46e4ff4135b4df55866a5df9af963e3d6ff218, you were actually undoing the changes from that old commit itself, not rolling back the commits that came after it. That's why you ran into unexpected behavior.
正确操作:撤销后续的两个提交
Your goal is to get back to the state of 6e46e4f..., but keep the "added B2" and "added C3" commits in your history. To do this, you need to revert those two later commits (the ones you want to undo), not the old base commit.
方法1:逐个撤销(推荐,减少冲突概率)
- First, check your commit log to get the full hashes of the "added B2" and "added C3" commits. You can run:
This will show you a condensed log like:git log --onelinedef456 (HEAD -> main) added C3 abc123 added B2 6e46e4f your target base commit ... - Revert the newest commit first (to avoid unnecessary conflicts):
This will open your default text editor (like Vim) with a pre-filled commit message explaining that you're reverting "added C3". Just save and exit the editor:git revert def456- For Vim: Press
Esc, then type:wqand hit Enter. - If you need to abort without saving, type
:q!instead.
- For Vim: Press
- Next, revert the "added B2" commit:
Repeat the editor steps to save the revert commit.git revert abc123
方法2:一次性撤销范围提交
If you want to revert all commits after 6e46e4f... in one go, use a commit range:
git revert 6e46e4ff4135b4df55866a5df9af963e3d6ff218..HEAD
This command will automatically create a revert commit for every commit between 6e46e4f... and your current HEAD. If Git detects conflicts between the commits, it will pause and ask you to resolve them:
- Fix the conflicted files in your editor.
- Once fixed, stage the changes with
git add <conflicted-file>. - Continue the revert process with
git revert --continue. - If you want to cancel the entire operation, run
git revert --abort.
最终效果
After completing either method, your Git log will still show the original "added B2" and "added C3" commits, plus two new commits like Revert "added C3" and Revert "added B2". Your code will be back to the exact state it was in at commit 6e46e4f..., which is exactly what you wanted!
内容的提问来源于stack exchange,提问作者john smith

