Course lesson

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

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.

Duration
1 min
Access
Free
Transcript
Retained from source evidence

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.

After doing a git reset --hard HEAD~1, it removed the code in our app.js, but we want to get it back. We can look at git reflog, something used to look at all the different things you have done in your local git repository. You can see the latest resets you've done with that command, note the hashes which you'll be using later.

One thing to note is that we are trying to recover a hard reset, so the commit is considered abandoned and will get garbage collected eventually if we don't save it. git reflog will work to save commits, but only if they haven't been garbage collected by git yet.

Once you find the commit you need to return to to recover your code, use that hash and run git reset --hard {HASH}. It will then return your code back to its state. Using git log --oneline shows the regular commits, as well the old commit. After successfully recovering, remember to git push to store in Github to view.

✏️ Edit on GitHub