mancuoj

mancuoj

Better late than never.
github
twitter

What should I do if I accidentally commit to the wrong branch in Git?

First, undo the last commit on the wrong branch, then stash your changes:

git reset HEAD~ --soft
git stash

Switch to the correct branch, pop out your temporarily saved changes and recommit:

git checkout correct-branch
git stash pop
git add .
git commit -m "your message"

Another method#

The git cherry-pick command is used to apply a specific commit from another branch to the current branch.

So, we can apply the latest commit from the wrong branch to the correct branch:

git checkout correct-branch
git cherry-pick wrong-branch

Finally, delete this commit from the wrong branch:

git checkout wrong-branch
git reset HEAD~ --hard
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.