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.

Umer Mansoor
Written by Umer Mansoor Follow
Hi, I am Umer. I live in the San Francisco Bay Area and it is where I work. Since 2011, I have worked at startups, mobile gaming and internet companies. If you have any questions, feel free to message me.

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

Join Newsletter
Enter your email address to receive a very occasional newsletter. I'll never spam or sell your email.