Repaso
Español
Maven, Git & SDLCAdvancedVCS-19

You ran git reset --hard by mistake and "lost" commits. What can save you?

Options

  1. Nothing; the commits are gone forever after a reset
  2. git reflog shows where HEAD was, so you can restore it (Correct option)
  3. Reinstalling Git on the machine you are working on
  4. Deleting the .git folder and cloning the repo again

Answer

git reflog shows where HEAD used to point, so you can find the commit hash and restore it with git reset or git checkout

Why

Git rarely deletes commits immediately. git reflog is a local log of every position HEAD has been in (commits, resets, checkouts, rebases).

Find the hash from before the mistake (HEAD@{3}) and restore it: git reset --hard <hash> or create a branch there: git branch rescue <hash>.

Unreferenced commits are kept for roughly 30 to 90 days before garbage collection. Uncommitted changes lost by a hard reset, however, cannot be recovered this way.

git reflog
git branch rescue HEAD@{2}

Remember

reflog = Git's undo history for HEAD.

Key terms

Practice this question in Repaso