Recover Local Changes from `git reset --hard` with `git reflog`

Chris Achard
InstructorChris Achard
Share this video with your friends

Social Share Links

Send Tweet

If you've removed a commit with git reset --hard, it's still possible to recover the commit using git reflog to look up the commit hash.

Once we find the right commit hash, we can reset our branch back to that commit hash with git reset --hard [HASH]

NOTE! git will actually garbage collect abandoned commits (every 30 days or so - so not very often) - so you can't recover from a reset --hard forever; which is why it's recommended to avoid --hard if you ever want to references those changes.

Instructor: [0:00] We just did a git reset --hard back one which removed our function from app.js. We really want to get that function back so let's take a look at how we might do that. For that, we're going to use git rough log which is a really powerful way to look at all the different things you've done in your local Git repository.

[0:21] For example, you can see the three latest resets that we've done and this last one was the reset hard. Now, we want to recover this commit here, this take three commit, but one thing to note is that this commit, because we reset hard, is now abandoned and will actually get garbage collected eventually if we don't save it.

[0:40] Rough log will work to save commits but only if they haven't been garbage collected by Git yet. We want to reset master to this commit to recover it so we can take the hash and we can git reset --hard back to that hash. Now we have our function back in app. If we do a git log oneline, we can see that we have our regular commits, and then we have the take three commit back on as master.

[1:10] We used reset --hard both to get rid of this commit by resetting to this commit, but also to recover it again from the ref log. Let's push this up to GitHub before we make any more mistakes. This is up in GitHub, so we can check it out there, as well.