Move a GIT commit to another branch

July 29, 2023

When accidentaly commited a change into the wrong branch

Sometimes changes gets commited into the wrong branch and needs to be moved to the correct branch.

This is a simple step by step solution to move the changes into the correct branch.

Get the commit into the correct branch

Find and copy the commit hash

Checkout, or create, the intended branch

git checkout -b bug/The-bug-fix  origin/bug/The-bug-fix

Then use cherry-pick to pick the commit from the “wrong” branch into the current one

git cherry-pick <commit-hash>

Remove the commit from the branch where it was wrongly commited

Checkout the branch that was accidentaly used, the next step is to remove the commit from the branch. The command below will remove last commit

git reset --hard HEAD~1

If we already pushed it to a remote repository, we need to force an update to the remote. This can however cause problems if anyone else has fetched from that repository.

git push origin HEAD --force

A better approach is probably to revert the commit and then push it.

git revert HEAD
git push origin

Then precede with a normal pull request, and everybody will be happy