my-git

Committed to Wrong Branch

提交到了错误分支,先判断是否已经 push。

还没 push 时很好处理。已经 push 后,要优先避免破坏公共历史。

先检查

git status --porcelain
git branch --show-current
git log --oneline --decorate -5

还没 push

假设你在名为 main 的分支上误提交了最后一个 commit,本来应该在 feat/right-branch。这里的 main 只是示例,实际要用检查结果里的错误分支名。

以下流程只适用于最后一个 commit 尚未 push、没有协作者依赖、并且 git status --porcelain 没有输出的情况。只要有 staged、unstaged 或 untracked 内容,就停止在 reset 前并保留现场。

git branch feat/right-branch
git reset --hard HEAD~1
git switch feat/right-branch

这会把当前 commit 保留到新分支,再让原分支回到提交前。

已经 push

如果已经 push 到公共分支,优先用 revert 修正原分支:

git revert <commit-sha>

再把正确 commit cherry-pick 到目标分支:

git switch feat/right-branch
git cherry-pick <commit-sha>

如果多个 commit 都错了

可以创建目标分支后,批量 cherry-pick:

git switch -c feat/right-branch
git cherry-pick <oldest-sha>^..<newest-sha>

执行前先确认 commit 范围。

避免再次发生

延伸阅读