Learn

Going back

Git

checkout, reset, revert, reflog. The rescue tools when you messed something up.

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:

shell
git restore README.md

If you already staged changes and want to unstage them (without losing the content):

shell
git restore --staged README.md

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.

shell
git revert HEAD

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.

shell
git reset --soft HEAD~1

--mixed mode (default): commits are undone, files are unstaged but changes remain.

shell
git reset HEAD~1

--hard mode: commits are undone and changes are DELETED. Unrecoverable without reflog.

shell
git reset --hard HEAD~1

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.

shell
git reflog

You see a list of entries with identifiers like HEAD@{2}. To go back to a specific state:

shell
git reset --hard HEAD@

Recover a file from an old commit

If you only want to recover a single file from a specific commit, without touching the rest:

shell
git restore --source a3f5b6c README.md

The file returns to its state in commit a3f5b6c, ready to stage or discard.

git-scm.com - git reset git-scm.com - git revert git-scm.com - git reflog

Related

See also · gitWorking with branches

Check off steps to unlock what comes next

Back to course