0
0
GitDebug / FixBeginner · 3 min read

How to Fix a Commit Made on the Wrong Git Branch

If you accidentally commit on the wrong branch, use git cherry-pick to copy the commit to the correct branch and then remove it from the wrong branch with git reset --hard HEAD~1. Alternatively, you can use git stash before switching branches to avoid this issue.
🔍

Why This Happens

This happens when you make a commit while your Git HEAD is on the wrong branch. It’s like writing a note on the wrong notebook page by mistake. Git records your changes in the current branch, so the commit ends up where you didn’t want it.

bash
git checkout wrong-branch
# Make some changes
git add .
git commit -m "Commit on wrong branch"
Output
On branch wrong-branch Changes committed successfully.
🔧

The Fix

First, switch to the correct branch. Then use git cherry-pick with the commit hash to copy the commit there. Finally, go back to the wrong branch and remove the commit using git reset --hard HEAD~1 to undo it completely.

bash
git checkout correct-branch
# Copy the commit from wrong branch
git cherry-pick <commit-hash>

git checkout wrong-branch
# Remove the wrong commit
git reset --hard HEAD~1
Output
On branch correct-branch [correct-branch abc1234] Commit on wrong branch 1 file changed, 1 insertion(+) On branch wrong-branch HEAD is now at previous-commit-hash Previous commit message
🛡️

Prevention

Always check your current branch with git status before committing. Use git stash to save changes temporarily if you need to switch branches. Consider using branch naming conventions and Git hooks to remind you which branch you are on.

⚠️

Related Errors

Other common mistakes include committing with uncommitted changes on multiple branches or accidentally pushing wrong commits to remote. These can be fixed by git revert or force pushing carefully after rewriting history with git reset.

Key Takeaways

Always verify your current branch with git status before committing.
Use git cherry-pick to move commits between branches safely.
Undo wrong commits with git reset --hard HEAD~1 if not pushed.
Use git stash to save work before switching branches.
Adopt branch naming and Git hooks to reduce mistakes.