Appearance
13.11.4 — Undoing Things Safely
It is 5:40 pm. You typed git reset --hard to fix one small thing, and the last two hours of your work are gone from the screen.
Or you pushed a commit with a typo that breaks the build, and the whole team is now pulling it.
Or you committed your database password.
Every developer has a day like this. The people who stay calm are not braver. They know that almost nothing in Git is lost, and they know which command fits which mistake. This page gives you that map.
1. Two questions pick the right command
Before you type anything, ask yourself two questions.
Question one: where is the mistake?
- In your files, not committed yet.
- In a commit on your laptop.
- In a commit that is already pushed.
Question two: has anyone else got this commit?
If the answer is no, you may rewrite history, because only you will ever see the old version. If the answer is yes, you must not rewrite it. You add a new commit that undoes the old one. Rewriting something other people already have forces all of them to untangle your change from theirs.
That single rule decides nearly every case. Here is the whole map in one picture. Start at the top.
The rest of the page goes through each box, with a real run for each.
2. Before you commit: files and the staging area
Throw away an edit: git restore file
You changed cart.ts, it is wrong, and you want the last committed version back.
text
$ echo "// oops, a mistake" >> cart.ts
$ git status -s
M cart.ts
$ git restore cart.ts
$ git status -s
$git restore cart.ts replaces the file in your folder with the version from the staging area (or, if nothing is staged, the last commit). The edit is gone.
This one cannot be undone. Git never stored that edit anywhere. It lived only in your file. So read git status first, and be sure. The same warning applies to git restore . (every file), which people type in a hurry.
Take something out of the staging area: git restore --staged file
You staged a file by mistake, or you staged a debug line you did not mean to.
text
$ echo "// debug line" >> cart.ts
$ git add cart.ts
$ git status -s
M cart.ts
$ git restore --staged cart.ts
$ git status -s
M cart.tsThe M moved from the first column (staged) to the second (not staged). Your edit is still in the file. You only took it out of the waiting room. Older tutorials write git reset file for the same thing.
Get an old version of one file: git restore --source
You broke tax.ts and want the version from three commits ago, without moving anything else:
text
$ echo "broken" > tax.ts
$ git restore --source=HEAD~3 tax.ts
$ cat tax.ts
export function tax(amount: number): number {
return amount * 0.2;
}--source says "take the file from this commit instead of from the staging area". It works with any commit id or name (HEAD~3, a1b2c3d, v1.0). The file lands in your folder as an uncommitted change, so you can look before you commit.
The same command brings back a file you deleted. If you ran rm tax.ts by accident, git restore tax.ts puts it back.
Remove files Git does not know about: git clean
Build output and scratch files that are untracked are not touched by restore. git clean deletes them. It is dangerous, because untracked files have no history to bring them back. So always preview first.
text
$ git clean -n # -n = dry run: show what WOULD be removed
Would remove scratch.tmp
$ git clean -nd # -d = include untracked folders too
Would remove old-output/
Would remove scratch.tmp
$ git clean -fd # -f = really do it
Removing old-output/
Removing scratch.tmpGit requires the -f flag so you cannot do it by accident. Run -n every time.
3. Fixing the last commit: git commit --amend
You committed, then noticed a typo in the message, or you forgot to add a file.
text
$ git commit -q -m "Add discuont"
$ git commit --amend -m "Add discount and limits"
[main cd1a655] Add discount and limitsThat fixed the message. To add a forgotten file, stage it first, then amend without changing the message:
text
$ echo "// header" > header.ts
$ git add header.ts
$ git commit --amend --no-edit
[main 39a2dc6] Add limits module
2 files changed, 2 insertions(+)
create mode 100644 header.ts
create mode 100644 min.tsThe commit now contains both files.
An important detail. Look at the ids: the commit was 26563dc before the first amend and cd1a655 after. Amend does not edit the commit. It makes a new one and moves the branch to it.
git commit --amend does not edit commit C. It makes a new commit C′ from the same parent, and moves the label to it. The old C is left behind, still recoverable through the reflog for a while.Commits are immutable. Changing one means creating a replacement with a new id, from the same parent. That is why the rule from section 1 applies: only amend a commit that has not been pushed. If you amend a pushed commit, your laptop and the remote now disagree about what commit C is, and you will need a force push (Chapter 13.11.3 shows why that is risky).
4. Going back several commits: git reset
reset moves your branch label to a different commit. It has three modes, and they differ only in how far the change reaches into the three areas you met in Chapter 13.11.1.
reset moves the branch back. --mixed also empties the staging area. --hard also rewrites your files, and it is the only one that can lose work you had not committed.Read the figure by column. In all three, the branch moves back. They differ in what happens to the staging area and to your files.
Here is each one on the same example. We have a commit "Add limits module" that added two files, and we move back one commit with HEAD~1.
--soft: undo the commit, keep everything staged.
text
$ git reset --soft HEAD~1
$ git status -s
A header.ts
A min.ts
$ git log --oneline -3
cd1a655 Add discount and limits
827fba3 Add discount
e42d3f8 Add taxThe commit is gone from the log. But both files are still staged, ready to be committed again. Use this when the work is right and the commit is wrong: for example, to merge the last three commits into one with git reset --soft HEAD~3 followed by a single git commit.
--mixed: undo the commit, keep the files, unstage them. This is the default when you give no flag.
text
$ git reset --mixed HEAD~1
$ git status -s
?? header.ts
?? min.tsThe files are still in your folder (they show as untracked, because the commit that introduced them is gone). Nothing is staged. Use this when you want to split one big commit into several: reset, then stage and commit the pieces one by one with git add -p.
--hard: undo the commit and throw the files away.
text
$ git reset --hard HEAD~1
HEAD is now at cd1a655 Add discount and limits
$ ls
README.md cart.ts discount.ts limits.ts tax.tsheader.ts and min.ts have disappeared from the folder. This is the only mode that changes your files. If you had uncommitted edits, they are lost too:
text
$ echo "precious unsaved work" >> README.md
$ git reset --hard
HEAD is now at d6f42f1 Revert "Merge branch 'feature'"
$ tail -1 README.md
tweakThe line "precious unsaved work" is gone for good. It was never committed, so Git has no record of it. That is why reset --hard is the most dangerous everyday command in Git.
But a committed thing is different, and that leads to the safety net.
A useful shortcut: after a merge, a pull, a reset or a rebase, Git remembers where your branch was just before, in a name called ORIG_HEAD. If a git pull went badly, git reset --hard ORIG_HEAD puts the branch back to how it was before the pull.
5. The safety net: the reflog
We just ran reset --hard and lost two files. Were they lost?
text
$ git reflog -5
cd1a655 HEAD@{0}: reset: moving to HEAD~1
9ed6dd5 HEAD@{1}: commit: Add limits module, third time
cd1a655 HEAD@{2}: reset: moving to HEAD~1
5748197 HEAD@{3}: commit: Add limits module, again
cd1a655 HEAD@{4}: reset: moving to HEAD~1The reflog is a diary that Git keeps privately on your laptop. Every time HEAD moves (a commit, a switch, a reset, a merge, a rebase), Git writes one line: where it moved from, and why. The newest line is on top, numbered HEAD@{0}.
Line HEAD@{1} says "a commit named Add limits module, third time was here, id 9ed6dd5". That is the commit we thought we lost. The commit itself was never deleted. Only the label moved away from it.
git reset --hard HEAD~2, commits C and D look gone. But Git wrote down every place HEAD has been in the reflog. One more reset to that entry brings them back.To get it back, move the branch onto that entry:
text
$ git reset --hard HEAD@{1}
HEAD is now at 9ed6dd5 Add limits module, third time
$ ls
README.md cart.ts discount.ts header.ts limits.ts min.ts tax.tsBoth files are back. HEAD@{1} means "where HEAD was one move ago". You could also use the id: git reset --hard 9ed6dd5.
Recovering a deleted branch
The same trick brings back a branch you deleted. Remember that git branch -D prints the commit id. If you lost the output, the reflog has it:
text
$ git branch -D tmp-feature
Deleted branch tmp-feature (was 8552050).
$ git reflog -4
d6f42f1 HEAD@{0}: checkout: moving from tmp-feature to main
8552050 HEAD@{1}: commit: Work on tmp-feature
d6f42f1 HEAD@{2}: checkout: moving from main to tmp-feature
$ git branch recovered-feature HEAD@{1}
$ git log --oneline -2 recovered-feature
8552050 Work on tmp-feature
d6f42f1 Revert "Merge branch 'feature'"git branch <name> <id> creates a new label on that commit. The work is back under a new name.
What the reflog cannot do
There are three limits, and they are worth knowing before you need them.
- It never saw uncommitted work. The reflog records commits and moves. A file you edited but never committed is invisible to it. The one genuinely unrecoverable thing in Git is work you never committed. This is the best argument for committing early, even roughly. You can always tidy up later.
- It is local. It lives in your
.gitfolder. It cannot rescue something that was only ever on a colleague's laptop. - Entries expire. By default Git keeps entries for 90 days, and entries for commits that no branch reaches for 30 days. After that,
git gcmay delete them for real.
If you have no reflog entry at all, git fsck --lost-found lists "dangling" commits that no label points to. It is slow and shows ids without messages, but it has rescued people.
6. After you have pushed: git revert
Now the other case. The bad commit is already on the shared branch. Others have pulled it. You must not rewrite history.
git revert creates a new commit that does the exact opposite of an old one. The old commit stays in history. The history only grows.
text
$ git revert HEAD --no-edit
[main ab7019f] Revert "Add limits module, third time"
2 files changed, 2 deletions(-)
delete mode 100644 header.ts
delete mode 100644 min.ts
$ git log --oneline -3
ab7019f Revert "Add limits module, third time"
9ed6dd5 Add limits module, third time
cd1a655 Add discount and limitsThe log now shows the original commit and, on top of it, a commit called Revert "..." that deletes what it added. Anyone who pulls gets a normal, forward-moving change. No one's copy is invalidated.
git revert <id> works for any commit, not just the latest. Git undoes just that one commit's changes and keeps everything after it. If a later commit touched the same lines, you may get a conflict, and you resolve it as in Chapter 13.11.2.
You can also revert a revert. That re-applies the original change:
text
$ git revert HEAD --no-edit
[main 94792c9] Reapply "Add limits module, third time"Reverting a merge, and the trap that follows
A merge commit has two parents: parent 1 is the branch you merged into, and parent 2 is the branch you merged in. To undo a merge, Git needs to be told which side to keep. You say it with -m 1, meaning "keep parent 1".
text
$ git revert -m 1 HEAD --no-edit
[main d6f42f1] Revert "Merge branch 'feature'"
1 file changed, 1 deletion(-)
delete mode 100644 flag.tsThat works. Now comes a surprise that catches experienced engineers during a release rollback. Say the feature team fixes the problem and tries to merge their branch again:
text
$ git merge feature
Already up to date.Nothing happened. Git sees that every commit of feature is already part of main's history (the original merge brought them in), and it does not notice that you reverted the effect. The revert undid the changes, but the commits are still "merged" as far as Git can tell.
Worse, if the team adds new commits to the branch and merges again, only the new commits arrive, and you get a confusing conflict about a file that "was deleted":
text
$ git merge feature --no-edit
CONFLICT (modify/delete): flag.ts deleted in HEAD and modified in feature.The fix is to revert the revert first. That brings the changes back, and only then does merging the branch again make sense:
text
$ git revert d6f42f1 --no-edit
[main 017e38a] Reapply "Merge branch 'feature'"
1 file changed, 1 insertion(+)
create mode 100644 flag.ts
$ git merge feature --no-edit
Merge made by the 'ort' strategy.Now the new commits arrive cleanly. Write this down. It is the Git rollback story people tell in interviews.
7. I committed a secret
You pushed a password, an API key or a private key. This is an emergency, and the order matters.
Step one: assume it is stolen, and revoke it. Change the password, delete the key, rotate the token in the service that issued it. Do this first. Bots scan public repositories for secrets continuously, and a leaked key can be used within minutes. Chapter 8.6.1 covers how.
Step two: remove it from the repository. Deleting the file in a new commit does not help. The old commit still contains it, and anyone who cloned already has it. You must rewrite history so that no commit contains the secret. The recommended tool is git filter-repo:
bash
git clone --mirror git@github.com:ana/shop.git # (1) work on a fresh copy
cd shop.git
git filter-repo --path .env --invert-paths # (2) remove this file from every commit
git remote add origin git@github.com:ana/shop.git # (3) filter-repo removes the remote on purpose
git push origin --force --all # (4) replace every branch on the remote
git push origin --force --tags # (5) and every tag- A fresh copy, because
filter-reporefuses to run on a working copy with local changes. It protects you from rewriting something you cannot get back. --path .env --invert-pathsmeans "keep everything except this path". The file disappears from every commit it was ever in.- The tool deletes the
originremote after running, so that you cannot push the rewritten history by accident. You add it back deliberately. - and 5. The forced pushes replace the remote's history with the cleaned one.
This rewrites every commit that came after the secret, so all their ids change. Everyone on the team must then throw away their copy and clone again, or they may push the secret back in. Tell them first.
Step three: ask the hosting service to clear its caches (GitHub's support can do this), and check whether other copies, such as forks, still hold it.
The lesson: prevention is cheap and cleanup is expensive. Keep secrets out with .gitignore (Chapter 13.11.1) and a secret scanner on every push.
8. The commands that can lose work
If you remember only one list from this page, make it this one. These are the commands that destroy something Git cannot bring back.
| Command | What it destroys | Safer habit |
|---|---|---|
git restore file or git restore . | Uncommitted edits | Run git diff first, or stash |
git reset --hard | Uncommitted edits | Commit or stash first |
git clean -fd | Untracked files | Run git clean -nd first |
git push --force | Commits on the remote | Use --force-with-lease, and read what is there |
git branch -D | Nothing at first, but hides commits | Note the id it prints |
git stash drop or clear | Stashed changes | Check git stash list |
Notice the pattern. Everything on this list loses uncommitted or unpushed work. Anything you have committed stays in the reflog for weeks. So the cheapest insurance is a habit: commit before you try anything risky, even a rough "wip" commit. You can tidy it later with reset --soft or an interactive rebase.
9. When it has gone wrong: the quick table
| Situation | Fix |
|---|---|
| Typo in the last commit message | git commit --amend -m "new message" (before pushing) |
| Forgot a file in the last commit | git add file, then git commit --amend --no-edit |
| Staged the wrong file | git restore --staged file |
| Edited a file and want it back | git restore file (cannot be undone) |
| Committed on the wrong branch | git reset --soft HEAD~1, git switch right-branch, commit again |
Bad reset --hard | git reflog, then git reset --hard HEAD@{n} |
| Deleted a branch | git reflog, then git branch name <id> |
| Pushed a bad commit | git revert <id>, never rewrite shared history |
| Rolling back a merge | git revert -m 1 <merge-id>, and revert the revert before re-merging |
| Merge went wrong | git merge --abort, or git reset --hard ORIG_HEAD |
| Rebase went wrong | git rebase --abort, or reflog to before it |
| Committed a secret | Revoke first, then git filter-repo, then everyone re-clones |
| Lost commits and no reflog entry | git fsck --lost-found |
| Detached HEAD with commits | git branch rescue <id> before switching away |
What the interviewer will push on
Undo questions are the favourite way to separate people who use Git from people who fear it.
"What is the difference between git reset and git revert?" The checker here is whether you think about shared history. reset moves the branch label back, so it rewrites history: fine for local work, dangerous after a push. revert adds a new commit that cancels an old one, so history only grows: the safe choice for anything shared. A weak answer lists the commands only. A strong one gives the rule: "never rewrite what others already have".
"Explain --soft, --mixed and --hard." Name the three areas: commits, staging area, working files. Soft moves only the branch. Mixed also clears the staging area. Hard also overwrites the files. Say which one can lose work: only --hard, and only the uncommitted work.
"I ran git reset --hard and lost my commits. Can you get them back?" Yes, through the reflog: find the entry, git reset --hard HEAD@{n}. Then add the limit that shows depth: uncommitted work is not in the reflog, and entries expire after about 90 days.
"How do you undo a merge that is already pushed?" git revert -m 1 <merge-commit>. Explain -m 1 as "keep the first parent, the branch I merged into". Then volunteer the trap: re-merging the branch does nothing until you revert the revert.
"What does git commit --amend do to the commit?" It does not edit it. It creates a new commit with a new id and moves the branch. That is why it is only safe before you push.
"You committed a password. What do you do?" Revoke the password first. Then rewrite history with git filter-repo, force-push, and have the team re-clone. The common wrong answer is "delete the file and commit again".
One thing to volunteer: say that you commit work-in-progress often, because the reflog protects committed work for weeks but cannot see uncommitted edits. It shows you understand what Git actually protects.
Recall
- Two questions choose the command: where is the mistake (files, a local commit, a pushed commit) and does anyone else have this commit? If yes, never rewrite; add a new commit.
git restore filediscards edits (cannot be undone).git restore --staged fileunstages.git restore --source=<commit> filepulls an old version of one file.git clean -npreviews,-fddeletes untracked files.git commit --amendmakes a new commit with a new id; use it only before pushing.git resetmoves the branch back.--soft: keep changes staged.--mixed(default): keep files, unstage.--hard: also overwrite files, and loses uncommitted work.ORIG_HEADis where the branch was before the last merge, pull or reset.- The reflog records every move of
HEAD, so committed work survives a bad reset, a deleted branch or a botched rebase:git reflog, thengit reset --hard HEAD@{n}orgit branch name <id>. It is local, expires (about 90 days), and cannot see uncommitted work. git revert <id>adds a commit that cancels an old one: the safe undo for shared history. A merge needs-m 1(keep parent 1). After reverting a merge, re-merging does nothing until you revert the revert.- A committed secret: revoke it first, then
git filter-repo, force-push, and everyone re-clones. Deleting the file in a new commit is not enough. - The commands that lose work all touch uncommitted or unpushed things:
restore,reset --hard,clean -fd,push --force,stash drop. Commit before anything risky.
Self-test: Why must you not amend a pushed commit? · What does each of the three reset modes do to the staging area and the files? · How do you recover a commit after reset --hard? · Why does re-merging a reverted branch do nothing? · What is the one kind of work the reflog cannot save?
Next: 13.11.5 opens the .git folder and shows what Git has been storing all along. Once you see it, the commands from these four pages stop being rules to memorise and become things you could have predicted.