How to Undo Git Reset With the --hard Flag

Ashok Chapagai Feb 02, 2024
  1. There Were Committed Changes, Now Vanished Because of git reset --hard
  2. Changes Were Staged but Not Committed
  3. Changes Were Neither Committed Nor Staged
How to Undo Git Reset With the --hard Flag

Sometimes you might want to reset the changes up to a particular commit. Suppose you opt for the git reset --hard <commit id> way to reset the changes but forgot that the --hard flag discards uncommitted changes on the local system and later realize the mistake. In that case, there are different scenarios from where you can recover the changes.

In this article, you will find ways to undo the changes depending upon different scenarios.

There Were Committed Changes, Now Vanished Because of git reset --hard

This situation is one of the most commonly occurring situations and the easiest one to recover changes of. If you run git reset --hard and have made modifications to the repository, run git reflog <branchname to list all the changes made in that branch, including resets. The output may look something like this,

116daf4 dev@{0}: reset: moving to HEAD~
adf3a51 dev@{1}: commit: changed authentication method
4f7fa8c dev@{2}: commit: updated readme
5eb37ca dev@{3}: commit (initial): Initial Commit

Now, we can see that the first log shows that we had reset the dev branch. Now, to recover the changes of commit dev@{1} or adf3a51, you can run the command,

git reset --hard adf3a51

It will undo the changes up to that commit.

Changes Were Staged but Not Committed

Recovering the staged but not committed changes is a bit difficult than the method above, but it is still doable. Firstly, you can use the git fsck --lost-found command to list all the commit hashes that were dangling before you used the command git reset --hard. You can use git show <commit_hash> to see what the commit hash holds. Now that you have the dangling commit hash you were looking to reset, use the command git reset --hard <commit_hash again with the retrieved commit hash to get to the desired commit.

Changes Were Neither Committed Nor Staged

If you are still reading and are stumbled upon this method, then there might not be a way to undo the git reset --hard command since git does not store changes that you don’t add or commit to it. If you refer to the documentation for git reset and the --hard section, it says, resets the index and working tree. All changes to the tracked files in the working tree since are discarded.

Since it does not seem possible to recover the data from that state without much of a hassle, it will be wiser to let that situation not arise and know of the command you were about to use and its flags as well.

Ashok Chapagai avatar Ashok Chapagai avatar

Ashok is an avid learner and senior software engineer with a keen interest in cyber security. He loves articulating his experience with words to wider audience.

LinkedIn GitHub

Related Article - Git Reset