CH.09 · 12 MIN · PART 2

Mistakes are fixable.

Git is a safety net. Learn which undo to use, from gentle to dangerous, and how to tell them apart.

restoreamendresetrevertreflog
Commit checkpoints with a rewind arrow and recovery clock010203GO BACKreflogFOUNDAGAIN.

Pick the undo that fits

least scary first
1

Edited, not staged

git restore f puts the committed version back.

2

Staged by mistake

git restore --staged f unstages it. The file is untouched.

3

Typo in the last message

git commit --amend -m "new message" replaces the last commit. Only do this before you share it.

4

Wrong last commit

git reset --soft HEAD~1 keeps your work staged. --hard discards it.

5

Already shared

git revert HEAD --no-edit adds a new commit that cancels the old one. History is never rewritten.

6

Lost a commit

git reflog lists where HEAD has been. Copy the spot you want and git reset --hard HEAD@{1} goes back.

What does each undo lose?

read before you type
command
what changes
what can be lost
git restore f
Working file goes back to the last commit or staged copy
Your uncommitted edits to that file. Gone for good.
git restore --staged f
Takes the file out of staging
Nothing
git commit --amend
Replaces the last commit with a new one
Nothing. The old commit is still in the reflog for a while.
git reset --soft HEAD~1
Moves the branch back one commit, keeps files and staging
Nothing
git reset --hard HEAD~1
Moves the branch back and resets files to match
Uncommitted edits are gone for good. The removed commit is recoverable through the reflog, for a while.
git revert HEAD
Adds a new commit that undoes an old one
Nothing

Rule of thumb: work that was committed is hard to lose. Work that was never committed is not. The reflog is a safety net, not a vault: it forgets old entries after a while. Other commands can also discard work, for example git clean and deleting files, so slow down when a command says "force" or "hard".

When it goes wrong

real messages, plain meaning
fatal: ambiguous argument 'HEAD~5': unknown revision or path not in the working tree.You went further back than your historyRun git log --oneline to count your commits first.
error: your local changes would be overwritten by revert.Uncommitted work is in the wayCommit it or restore it, then try again.
Author identity unknownGit needs your name and email to record amend and revertSee Chapter 5.

Time machine: the reflog

interactive

The reflog remembers every place HEAD has been, even commits you reset away. Slide back to find them.

Reflog film stripDrag the slider. Each frame is one move HEAD made.

History at this moment

todo.txt at this moment

Go back here

Practice: undo a commit

hands-on

Amend a message, try the gentle undo, then the dangerous one, then get it back with the reflog and finish with a revert.

1

Loading

practice terminal · bash-style

Quick check

1 / 3

Pick an answer.
Git, Visually · Parts 1 and 2 · English