Member-only story

How to recover a git commit that is reset or discarded

Calm down! You can get it back!

Lynn G. Kwong
4 min readNov 13, 2020

We can make all kinds of mistakes when we write code. It is normal to make mistakes, but we should know how to solve the problem efficiently. In this article, I will show you an efficient way to recover a git commit that is reset or discarded accidentally.

Photo by Martin Sanchez on Unsplash.

When we write code, sometimes we may use git reset HEAD~1 to reset the HEAD of our feature branch. As we know, HEAD is the last commit of the current branch and thus HEAD~1 means the second to last commit of the current branch. With this command, the HEAD is set to the second to last commit and the original last commit is discarded. This command is useful if you want to re-organize your last commit, for example, to split it into several ones.

By default, the --mixed option is used for git reset HEAD~1, which means to move the changes made in the last commit from the local repository to the working directory. This is the behavior we normally want. Besides the default--mixed option, there are two other options that can be used. The first one is --soft, which moves the changes from the local repository to the staging area. The other one is --hard which discards the changes from the local repository, the staging area and also the working directory. This is where the danger comes from.

--

--

Lynn G. Kwong
Lynn G. Kwong

Written by Lynn G. Kwong

I’m a Software Developer (https://youtube.com/@kwonglynn) keen on sharing thoughts, tutorials, and solutions for the best practice of software development.

No responses yet