Git Tips - Undoing Accidental Commits

Umer Mansoor Umer Mansoor Follow Nov 13, 2016 · 1 min read

Here are couple of git undo’s to get yourself out of trouble. Before you use anything from this post, please make a copy of the your working directory and store it somewhere safe. Git can be very unforgiving and you may lose your changes without any warning.

Accidentally committed to master instead of a new branch

Use the commands below if you have accidentally committed your changes to the master branch instead of a new branch but haven’t pushed them to the remote repository yet.

# Create a new branch copying current state of master
git branch new-branch
# Restore master to second to last commit.
git reset --hard HEAD^
# Switch to the new branch to see your changes.
git checkout new-branch

Accidentally committed to the wrong branch

git cherry-pick <commit-hash> is a handy command to choose a commit from one branch and apply it to another.

# Note the commit-hash you want to move
git log
# Restore branch to second to last commit
git reset --hard HEAD^
# Switch to the right branch
git checkout right-branch
# Apply the commit to the right branch
git cherry-pick commit-hash

Till next time.


You May Also Enjoy

If you like this post, please share using the buttons above. It will help CodeAhoy grow and add new content. Thank you!

Comments (1)

Henrik Olsen

Another way to cherry pick the last commit from the wrong brach.

git checkout right-branch
git cherry-pick wrong-branch
git checkout right-branch
git reset --hard HEAD~

Speak Your Mind

Read free Software Algorithms and Computer Science Books by CodeAhoy Learn.

Introduction to Recursion and Backtracking

Sorting Algorithms

Introduction to C Programming Language

And More...