CS Fundamentals Trainer · Guides
Git: undoing mistakes with the reflog, reset, revert, rebase and recovery
A practical guide to getting out of trouble in Git: the three areas (working tree, index, repository), what each reset mode touches, the reflog as a recovery tool with its limits, reset against revert, amend and fixup with autosquash, interactive rebase, cherry-pick, merge conflicts (zdiff3, rerere), stash, force-with-lease, and finding what changed.
9 min read
Most people learn Git as a list of commands and then freeze the first time something goes wrong: a commit on the wrong branch, a reset --hard that ate an afternoon of work, a merge full of conflict markers. The way out is a small mental model plus a safety net. Git almost never destroys committed work; it moves pointers, and the old commits stay in the object store for weeks. This guide explains the three places where your changes live, the commands that move them, the reflog that lets you undo almost anything, how to rewrite history safely before it is shared, how to handle conflicts, and how to push without hurting a teammate. Every command output below came from a real run with Git 2.43. For the object model behind it (blobs, trees, commits, refs) and for bisect, branching strategies and CI, see the guide "Git internals and CI/CD pipelines".
1. Three places and who touches them
A change moves through three areas, and almost every undo question is "which area do I want to reset?".
| Area | What it is | Moved by |
|---|---|---|
| Working tree | the files on disk | your editor, git restore, git switch, git stash |
| Index (staging area) | the snapshot that the next commit will record | git add, git restore --staged, git reset |
| Repository | commits and the branch pointer HEAD | git commit, git reset, git revert, git rebase |
git reset has three modes that differ only in how far they go:
| Command | Moves the branch pointer | Resets the index | Overwrites the working tree |
|---|---|---|---|
git reset --soft <c> | yes | no | no |
git reset --mixed <c> (default) | yes | yes | no |
git reset --hard <c> | yes | yes | yes |
Only --hard (and git restore <file>, git checkout -- <file>, git clean) can lose uncommitted work, because that work was never in the repository. Everything that was committed is recoverable, as the next section shows.
2. The safety net: the reflog
Every time HEAD or a branch moves, Git writes a line to the reflog, a private, local diary of where your pointers have been. After a bad reset, the commits are not gone, they are just unreachable from any branch:
$ git reset --hard HEAD~2
$ git log --oneline
0decb64 c1
$ git reflog
0decb64 HEAD@{0}: reset: moving to HEAD~2
2a2c20c HEAD@{1}: commit: c3
703d80e HEAD@{2}: commit: c2
0decb64 HEAD@{3}: commit (initial): c1
$ git reset --hard HEAD@{1}
$ git log --oneline
2a2c20c c3
703d80e c2
0decb64 c1
Remember three facts about it:
- It is local: it is not pushed, and a fresh clone has no history of your mistakes.
- Entries expire. By default reachable entries are kept for 90 days and unreachable ones for 30 days (
gc.reflogExpire,gc.reflogExpireUnreachable), andgit gcthen deletes the objects. - It only knows about commits. Uncommitted changes you destroyed with
reset --hardare not in it. If you are about to do something risky, commit first (even a throwaway commit); it is cheap and reversible.
A detached HEAD is the other case where the reflog saves you: commits made there belong to no branch, and git switch -c rescue <sha> gives them a name.
3. Undoing a change: reset or revert?
git resetmoves the branch back, as if the later commits never happened. Use it on commits that exist only on your machine.git revert <c>adds a new commit that applies the opposite change. Use it on anything already shared, because it does not rewrite history; teammates just pull one more commit.
$ git revert --no-edit HEAD
$ git log --oneline | head -2
0ad11db Revert "c3"
2a2c20c c3
To revert a merge commit you must say which side to keep with -m 1 (usually the mainline). Reverting a merge also makes Git treat those changes as already merged, so merging the branch again later brings nothing; you must revert the revert first.
For single files use the newer, clearer commands (Git 2.23): git restore <file> throws away working-tree edits, git restore --staged <file> unstages, and git restore --source=<commit> <file> brings a version from the past. git switch changes branches and git switch -c name creates one.
4. Fixing the last commits
Wrong message, or you forgot a file: git commit --amend replaces the last commit (with the staged changes and a new message). It changes the commit's id, so only amend before pushing.
A fix that belongs to an earlier commit: commit it with --fixup, then let Git reorder it:
$ git commit -qa --fixup HEAD
$ git log --oneline | head -2
3328826 fixup! feat g
9744119 feat g
$ GIT_SEQUENCE_EDITOR=true git rebase -i --autosquash HEAD~2
$ git log --oneline | head -2
3e798ea feat g
0ad11db Revert "c3"
Interactive rebase (git rebase -i <base>) opens a to-do list with one line per commit. Change the word at the start of a line:
| Word | Effect |
|---|---|
pick | keep the commit |
reword | keep it, edit the message |
edit | stop here so you can change the commit |
squash / fixup | merge into the previous commit (fixup drops the message) |
drop | remove the commit |
Reordering lines reorders commits. If it goes wrong, git rebase --abort returns to the state before it started, and the reflog has the original tip.
5. Moving a commit between branches
git cherry-pick <sha> copies one commit onto the current branch as a new commit (new id, same change). Use it for a hotfix that must land on two branches, or when you committed on the wrong branch: cherry-pick onto the right one, then git reset --hard HEAD~1 on the wrong one. Many commits at once: git cherry-pick A..B. A cherry-picked commit can conflict like any merge, and Git will not know that two commits are "the same change", so avoid cherry-picking something you will later merge.
6. Merge conflicts
A conflict happens when both sides changed the same lines. Git stops, marks the files and waits:
<<<<<<< HEAD
B
=======
A
>>>>>>> a
Edit the file to the result you want, remove the markers, git add it, and finish with git commit (or git rebase --continue in a rebase). If you want out: git merge --abort or git rebase --abort, and the working tree returns to how it was.
Three settings make conflicts easier:
git config merge.conflictStyle zdiff3also shows the common ancestor between|||||||and=======, which tells you what each side changed. (This is the shape it printed in the test.)git config rerere.enabled true("reuse recorded resolution") remembers how you resolved a conflict and applies it again, which helps in long-lived rebases.git mergetoolopens your visual tool.
Rebasing resolves conflicts commit by commit and can repeat the same conflict; merging resolves them once, at the end.
7. Stash: putting work aside
git stash saves modified tracked files and cleans the working tree; git stash pop restores them (and drops the entry), git stash list shows them, and git stash -u includes untracked files. It is meant for short interruptions, such as switching branches for a quick fix. For anything that lives longer than an hour, a work-in-progress commit on a branch is safer than a stash: stashes have no branch, are easy to forget and can conflict when popped.
8. Pushing history you rewrote
Once a commit is pushed and others may have it, rewriting it forces everyone else to repair their branches. So: rewrite your own, unshared branches freely, and never force-push a shared branch such as main. When you must update your own feature branch after a rebase, use:
git push --force-with-lease
It overwrites the remote branch only if it still points where you last saw it, so you do not erase a commit a colleague pushed in the meantime. Plain --force has no such check. Many teams protect main with branch rules that reject force pushes entirely.
9. Finding what happened
git log -S"text"lists commits that added or removed that string;-G"regex"matches changed lines.git log --follow -- filefollows renames.git blame -L 10,20 fileshows who last changed each line;git blame -w -Cignores whitespace and detects moved code. Put noisy reformatting commits in.git-blame-ignore-revsand setblame.ignoreRevsFile.git bisect start BAD GOODbinary-searches the commit that introduced a bug; withgit bisect run <script>it does it automatically.git diff main...topic(three dots) shows whattopicchanged since it diverged.
A few safe deletions: git branch -d name refuses to delete an unmerged branch ("error: the branch 'dead' is not fully merged"), and -D forces it. The commits are still in the reflog if you regret it.
10. Common mistakes
- Running
reset --hardorclean -fdwith uncommitted work you wanted. - Amending or rebasing commits that were already pushed to a shared branch.
git push --forceinstead of--force-with-lease.- Using
revertfor a private mistake (noise) orresetfor a shared one (breaks teammates). - Resolving a conflict by choosing one side blindly instead of reading both.
- Panicking after a bad command instead of reading
git reflog. - Large "fix everything" commits that are impossible to revert or bisect.
- Committing secrets, then deleting them in a later commit: they remain in history. Rotate the secret and rewrite history if needed.
11. Things to mention in an interview
- Working tree, index and repository, and which command affects which.
reset(move pointers; soft/mixed/hard) versusrevert(new inverse commit) and why shared history needsrevert.- The reflog as the recovery tool, its limits (local, expiry, only commits).
rebase -iwithfixup/squash, and the rule "do not rewrite shared history".--force-with-lease,rerere,zdiff3andbisect.
Quick recap
Git moves pointers; commits survive. Check git status, commit before risky operations, and use git reflog when you think work is lost. reset for private history, revert for shared history, --force-with-lease if you must overwrite your own branch, and never force-push shared branches.
Sources
- Scott Chacon and Ben Straub, Pro Git, especially "Git Tools: Reset Demystified", "Rewriting History" and "Maintenance and Data Recovery".
- The Git project, documentation for git-reflog, git-reset, git-revert, git-rebase and git-push (
--force-with-lease). - The Git project, git-restore, git-stash and git-config (
merge.conflictStyle,rerere.enabled).
Practise this topic: DevOps & Cloud