| English | 中文 |
When committing to the wrong branch, first determine if it has been pushed.
It is easy to handle when not yet pushed. Once pushed, prioritize avoiding disruption to the public history.
git status
git branch --show-current
git log --oneline --decorate -5
Assume you accidentally committed the last commit to main, but it should have been in feat/right-branch.
git branch feat/right-branch
git reset --hard HEAD~1
git switch feat/right-branch
This preserves the current commit in a new branch and reverts the original branch to its pre-commit state.
If already pushed to a public branch, prioritize using revert to correct the original branch:
git revert <commit-sha>
Then cherry-pick the correct commit to the target branch:
git switch feat/right-branch
git cherry-pick <commit-sha>
You can batch cherry-pick after creating the target branch:
git switch -c feat/right-branch
git cherry-pick <oldest-sha>^..<newest-sha>
Verify the commit range before executing.
git branch --show-current before each commit