Git Interview Question 4: Reflog Recover Reset
Git Interview Questions · Test 1 · question 4 of 10
On your local branch feature/billing you meant to discard some unstaged edits. Instead you ran git reset --hard HEAD~2. Your last two commits, which were never pushed, no longer appear in git log, and you have not run any other command since.
How do you get the branch back to where it was before the reset?
Show answer and explanation
Answer:
A reset moves the branch pointer, but it doesn't delete the commits right away. Git records every move of HEAD and of each branch in the local reflog, and HEAD@{n} means "where HEAD was n moves ago." The latest entry (HEAD@{0}) is the reset itself, so HEAD@{1} is the commit HEAD pointed to just before it. Running git reset --hard HEAD@{1} moves the branch back there, and both commits are restored. The dropped commits remain recoverable until they are no longer referenced and garbage collection removes them. Reflog entries expire only after a long time.
Option A misunderstands revert. git revert creates a new commit that reverses a commit which is still in history. A reset isn't a commit, so there's nothing to revert. Reverting HEAD~2 would undo an even older commit.
Option B doesn't work because the commits were never pushed. The remote-tracking branch doesn't contain them, so resetting to it can't bring them back.
Option C is wrong. git reset never writes to the stash. The stash holds only changes you save with git stash, not commits.
References: git-reflog; Pro Git: Revision Selection (RefLog Shortnames)