You committed bad code, or you destroyed your working tree with a bad reset --hard? This lesson shows you the rescue commands, from least destructive to most destructive.
Discard uncommitted changes
If you modified a file but have not staged it yet, and you want to revert to the committed version:
If you already staged changes and want to unstage them (without losing the content):
Undo a commit with git revert (safe)
git revert creates a new commit that reverses the effects of the targeted commit. History is preserved, no existing commit is deleted. This is the safe method, especially if you have already pushed.
HEAD refers to the latest commit. You can also pass a hash: git revert a3f5b6c.
Move back in history with git reset
git reset moves the branch pointer to an earlier commit. There are three modes, from least to most destructive:
--soft mode: commits are undone, files remain staged. Useful for combining commits.
--mixed mode (default): commits are undone, files are unstaged but changes remain.
--hard mode: commits are undone and changes are DELETED. Unrecoverable without reflog.
The safety net: git reflog
git reflog is your last resort. It lists everything HEAD has pointed to over the past weeks, even after a reset --hard. It is Git's secret memory.
You see a list of entries with identifiers like HEAD@{2}. To go back to a specific state:
Recover a file from an old commit
If you only want to recover a single file from a specific commit, without touching the rest:
The file returns to its state in commit a3f5b6c, ready to stage or discard.
