Skip to content

Volume ITechnology

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.

Something went wrongNot committed yetstill in your filesCommitted, not pushedonly on your laptopAlready pushedothers may have itStaged by mistakegit restore --staged fEdit you do not wantgit restore fWrong message or filegit commit --amendSeveral commits wronggit reset --soft HEAD~ngit reset --mixed HEAD~nUndo one commitgit revert <id>Undo a mergegit revert -m 1 <id>Lost something? (a reset --hard, a deleted branch, a bad rebase)git reflog → find the commit → git reset --hard <id> or git branch name <id>
Start at the top and answer one question at a time. The answer to "has anyone else got this commit?" decides whether you may rewrite history or must add a new commit.

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.ts

The 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.tmp

Git 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 limits

That 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.ts

The 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.

BeforeABCmainHEADAfter git commit --amendABCC′mainHEADnew idold C: dropped from the branch
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.

The branch (commits)Staging areaWorking files--softmoves backkeptkeptChanges stay staged,ready to commitagain--mixed (default)moves backemptiedkeptChanges stay inyour files, but areno longer staged--hardmoves backemptiedoverwrittenChanges arethrown away.Cannot be undoneCommits that "disappear" from the branch are not deleted. The reflog still knows them (see below).
Read each column downwards. Every 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 tax

The 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.ts

The 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.ts

header.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
tweak

The 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~1

The 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.

ABCDmainHEADmain was heregit reflogHEAD@{0} reset: moving to HEAD~2HEAD@{1} commit: DHEAD@{2} commit: CHEAD@{1} is Dgit reset --hard HEAD@{1} moves main back onto D
After 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.ts

Both 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.

  1. 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.
  2. It is local. It lives in your .git folder. It cannot rescue something that was only ever on a colleague's laptop.
  3. Entries expire. By default Git keeps entries for 90 days, and entries for commits that no branch reaches for 30 days. After that, git gc may 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.

git reset --hard HEAD~1 : the label moves backABCmainHEADC is no longer on any branchgit revert HEAD : a new commit that cancels CABCC⁻¹mainHEADundoes what C did
Reset moves the label back, so commit C drops out of the history. That is fine for work only you have. Revert keeps C and adds a new commit on top that cancels it, so the history only grows. That is the only safe way to undo something other people already have.
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 limits

The 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.ts

That 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
  1. A fresh copy, because filter-repo refuses to run on a working copy with local changes. It protects you from rewriting something you cannot get back.
  2. --path .env --invert-paths means "keep everything except this path". The file disappears from every commit it was ever in.
  3. The tool deletes the origin remote after running, so that you cannot push the rewritten history by accident. You add it back deliberately.
  4. 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.

CommandWhat it destroysSafer habit
git restore file or git restore .Uncommitted editsRun git diff first, or stash
git reset --hardUncommitted editsCommit or stash first
git clean -fdUntracked filesRun git clean -nd first
git push --forceCommits on the remoteUse --force-with-lease, and read what is there
git branch -DNothing at first, but hides commitsNote the id it prints
git stash drop or clearStashed changesCheck 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 ​

SituationFix
Typo in the last commit messagegit commit --amend -m "new message" (before pushing)
Forgot a file in the last commitgit add file, then git commit --amend --no-edit
Staged the wrong filegit restore --staged file
Edited a file and want it backgit restore file (cannot be undone)
Committed on the wrong branchgit reset --soft HEAD~1, git switch right-branch, commit again
Bad reset --hardgit reflog, then git reset --hard HEAD@{n}
Deleted a branchgit reflog, then git branch name <id>
Pushed a bad commitgit revert <id>, never rewrite shared history
Rolling back a mergegit revert -m 1 <merge-id>, and revert the revert before re-merging
Merge went wronggit merge --abort, or git reset --hard ORIG_HEAD
Rebase went wronggit rebase --abort, or reflog to before it
Committed a secretRevoke first, then git filter-repo, then everyone re-clones
Lost commits and no reflog entrygit fsck --lost-found
Detached HEAD with commitsgit 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 file discards edits (cannot be undone). git restore --staged file unstages. git restore --source=<commit> file pulls an old version of one file. git clean -n previews, -fd deletes untracked files.
  • git commit --amend makes a new commit with a new id; use it only before pushing.
  • git reset moves the branch back. --soft: keep changes staged. --mixed (default): keep files, unstage. --hard: also overwrite files, and loses uncommitted work. ORIG_HEAD is 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, then git reset --hard HEAD@{n} or git 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.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet