Undo, stash and recover work in Git
Most Git mistakes are recoverable, but only if you pick the right command for where the change is. A change can be in the working tree (edited, not staged), in the index (staged), in a local commit, or in a commit you already pushed and others have pulled. Each place has its own safe undo, and the dangerous commands are the ones that discard working-tree changes, because those were never committed and Git has no record of them.
This page goes from the smallest undo to the largest: discarding edits, fixing the last commit, reverting shared commits, resetting local history, recovering “lost” commits with the reflog, and parking unfinished work with git stash. The examples use an invented OrdersPortal repository and were run with Git 2.43 in a throwaway repository; your hashes will differ.
Topics on this page
Section titled “Topics on this page”| Topic | Undoes | Rewrites history? |
|---|---|---|
| Restore files | Working-tree edits and staged changes | No |
| Amend the last commit | The message or content of the latest commit | Yes (one commit) |
| Revert a commit | A commit that is already shared | No, adds a new commit |
| Reset a branch | One or more local commits | Yes |
| Recover with the reflog | A reset, rebase or amend you regret | No |
| Stash work in progress | Nothing; it parks changes so you can switch tasks | No |
| Clean and untrack files | Untracked files, or files committed by mistake | No |
Restore files
Section titled “Restore files”git restore (Git 2.23 and later) is the dedicated command for file-level undo. git restore <path> replaces the working-tree copy with the version in the index, throwing away unstaged edits. git restore --staged <path> unstages a file: the index goes back to the version in HEAD, and your edits stay in the working tree. --source=<commit> restores a file as it was in any commit, for example git restore --source=HEAD~3 pricing.py. Older guides use git checkout -- <path> and git reset HEAD <path> for the same jobs; they still work, but restore cannot accidentally switch branches.
git restore --staged refund.txt # unstage, keep the editgit restore refund.txt # discard the editgit restore . # discard every unstaged edit in the treePitfalls:
- Discarded edits are gone.
git restore <path>andgit restore .delete uncommitted work that Git never stored. If in doubt,git stashfirst. restoredoes not touch untracked files. New files you never added stay put; usegit cleanfor those.
Amend the last commit
Section titled “Amend the last commit”git commit --amend replaces the most recent commit with a new one built from the current index. Use it to fix a typo in the message, add a file you forgot to stage, or drop a debug line. --no-edit keeps the existing message. Because amend creates a new commit with a new hash, it is a small history rewrite: harmless before you push, and a force push (with --force-with-lease) afterwards.
git add invoice.txtgit commit -m "Add invocie"# notice the typo and a missing changegit add invoice.txtgit commit --amend -m "Add invoice export"git log --oneline -2Output:
086fb97 Add invoice export2dfbf30 Revert "Automate refunds"Pitfalls:
- Only amend unshared commits. Amending a commit others have pulled has the same effect as rebasing it.
- Older commits need interactive rebase. To fix a commit further back, use
git commit --fixup=<commit>andgit rebase -i --autosquash, described in Merge, rebase and cherry-pick.
Revert a commit
Section titled “Revert a commit”git revert <commit> creates a new commit that applies the inverse of an earlier one. History is not rewritten, so it is the correct undo for anything already pushed to a shared branch: everyone pulls the revert like any other commit. It works for any commit in history, not just the last one, and --no-commit lets you revert several commits and commit the result once. Reverting a merge commit needs -m 1 to say which parent is the mainline.
git revert --no-edit HEADgit log --onelineOutput:
[main 2dfbf30] Revert "Automate refunds" 1 file changed, 1 insertion(+), 1 deletion(-)2dfbf30 Revert "Automate refunds"d7ea637 Automate refunds276b1e9 Add refund flow6df936e Add order statusPitfalls:
- Reverting a merge has a long tail. After
git revert -m 1 <merge>, merging the same branch again does not bring the reverted changes back, because Git considers those commits already merged. To reintroduce them, revert the revert. - Revert can conflict. If later commits touched the same lines, resolve the conflict as in a merge and run
git revert --continue.
Reset a branch
Section titled “Reset a branch”git reset <commit> moves the current branch pointer (and HEAD) to another commit. The mode decides what happens to the changes in the commits you moved past:
--softkeeps them staged, ready to commit again (useful to squash the last few commits into one).--mixed, the default, keeps them in the working tree but unstaged.--harddiscards them from the index and the working tree.
git reset --soft HEAD~1; git status --shortgit commit -q -m "Automate refunds"git reset HEAD~1; git status --shortgit commit -qam "Automate refunds"git reset --hard HEAD~1; git status --short; cat refund.txtOutput:
M refund.txtUnstaged changes after reset:M refund.txt M refund.txtHEAD is now at 276b1e9 Add refund flowrefund = manualThe first M is in the left column (staged), the second in the right column (unstaged), and after --hard the tree is clean with the old content back.
Pitfalls:
--hardalso destroys uncommitted edits. Commits you reset away can be recovered from the reflog; edits that were never committed cannot.- Do not reset shared branches. Resetting
mainand force pushing removes commits from everyone’s history. Use revert on shared branches. git reset --hard origin/mainis a sledgehammer. It makes your branch match the remote exactly and throws away local commits and edits; rungit statusandgit log origin/main..first.
Recover with the reflog
Section titled “Recover with the reflog”Every time HEAD or a branch moves (commit, reset, rebase, amend, checkout), Git records the old position in the reflog. git reflog lists those positions as HEAD@{n}, newest first. A commit that no branch points to any more is still in the object database and still listed in the reflog, so “I reset the wrong branch” or “my rebase went wrong” is usually a one-line fix: find the entry from before the mistake and reset or branch to it.
git reflog -4git reset --hard HEAD@{1}cat refund.txtOutput:
276b1e9 HEAD@{0}: reset: moving to HEAD~1d7ea637 HEAD@{1}: commit: Automate refunds276b1e9 HEAD@{2}: reset: moving to HEAD~1d7ea637 HEAD@{3}: commit: Automate refundsHEAD is now at d7ea637 Automate refundsrefund = automaticCreating a branch at the entry (git switch -c rescue d7ea637) is a safer alternative when you are not sure.
Pitfalls:
- The reflog is local and it expires. It is never pushed or cloned. By default
git gcexpires entries after 90 days, and after 30 days for entries no longer reachable from a branch tip (gc.reflogExpireandgc.reflogExpireUnreachable). - Each branch has its own reflog too.
git reflog show feature/discountsshows where that branch pointed, which helps after a bad rebase.
Stash work in progress
Section titled “Stash work in progress”git stash (short for git stash push) saves your uncommitted changes, staged and unstaged, as a stash entry and returns the working tree to HEAD. Use it when an urgent fix interrupts a half-finished task and the work is not ready to commit. By default only tracked files are saved; -u (--include-untracked) also saves new files, and -a (--all) adds ignored files. -m gives the entry a readable name, and pathspecs stash only some files: git stash push -m "pricing only" -- pricing.py.
git stash pop reapplies the newest entry and drops it; git stash apply stash@{2} reapplies a specific entry and keeps it. git stash list, git stash show -p stash@{0}, git stash drop and git stash clear manage the stack. If the branch has moved on so far that a pop would conflict, git stash branch <name> stash@{0} creates a branch at the commit where you stashed, applies the entry there and drops it.
git stash push -u -m "WIP: dashboard filters"git stash listgit stash show --include-untracked stash@{0}git switch main # fix the urgent bug, commit, come backgit switch feature/dashboard-filtersgit stash popOutput (abridged):
Saved working directory and index state On feature/dashboard-filters: WIP: dashboard filtersstash@{0}: On feature/dashboard-filters: WIP: dashboard filters dashboard.txt | 2 +- presets.txt | 1 + 2 files changed, 2 insertions(+), 1 deletion(-)...Dropped refs/stash@{0} (4eb2790d37f8bcdb8ecdd61d6d881d3299a9215a)When a pop conflicts, Git applies what it can, marks the conflict, and keeps the entry:
CONFLICT (content): Merge conflict in dashboard.txtThe stash entry is kept in case you need it again.Resolve the file, then git stash drop once you are happy.
An alternative is a work-in-progress commit on your branch: git commit -am "WIP: do not merge", later undone with git reset --soft HEAD~1. A WIP commit can be pushed as a backup and shows up in history; a stash is local and invisible to teammates.
Pitfalls:
- Untracked files are left behind without
-u. A plaingit stashleaves new files in place, and they follow you to the other branch. - Stashes are local and easy to forget. They are not pushed, and a long stash list loses meaning. Name entries with
-mand turn anything older than a day into a branch. - A dropped stash is hard to find. It is not in the normal reflog; recovering it means searching unreachable commits with
git fsck --unreachable. Preferapplyplus a deliberatedropfor anything valuable.
Clean and untrack files
Section titled “Clean and untrack files”git clean deletes untracked files. Always preview with -n (dry run) first; -f deletes files, -d includes directories, and -x also deletes ignored files such as build output. git rm --cached <path> stops tracking a file but leaves it on disk, which is the fix when a generated file or a local config was committed by mistake; add it to .gitignore in the same commit so it does not come back.
git clean -n # previewgit clean -fd # delete untracked files and directoriesgit rm --cached appsettings.Local.jsonecho "appsettings.Local.json" >> .gitignoregit commit -am "Stop tracking local settings"Pitfalls:
- Untracking does not remove the file from history. If the file contained a secret, rotate the secret immediately; removing it from old commits requires a history rewrite with a tool such as
git filter-repo, and the secret should be treated as leaked anyway. git clean -xremoves ignored files. That includes.envfiles and local databases; read the-noutput.
Choosing between them
Section titled “Choosing between them”| You want to undo… | Use |
|---|---|
| Unstaged edits to a file | git restore <path> |
| Staging of a file | git restore --staged <path> |
| The message or content of your last, unpushed commit | git commit --amend |
| A commit that is already on a shared branch | git revert <commit> |
| Your last local commits, keeping the changes | git reset --soft HEAD~n or git reset HEAD~n |
| Your last local commits and their changes | git reset --hard HEAD~n |
| A reset, rebase or amend you regret | git reflog, then git reset --hard HEAD@{n} |
| Nothing yet; you need a clean tree for a few minutes | git stash push -u -m "..." |
Interview questions
Section titled “Interview questions”What is the difference between git reset and git revert?
Reset moves the branch pointer and removes commits from the branch’s history; it rewrites history and is for local work. Revert adds a new commit that cancels an earlier one; history is preserved, so it is the right tool for shared branches.
Explain --soft, --mixed and --hard.
All three move the branch. --soft leaves the undone changes staged, --mixed (the default) leaves them in the working tree unstaged, and --hard discards them from both. Only --hard can lose uncommitted work.
You ran git reset --hard HEAD~3 by mistake. How do you get the commits back?
Run git reflog, find the entry before the reset (typically HEAD@{1}), and run git reset --hard HEAD@{1} or create a branch at that hash. It works because the commits still exist; the reflog keeps them reachable for at least 30 days by default.
When would you choose git stash over a WIP commit?
Stash for short interruptions on your own machine when the work is not worth a commit. A WIP commit when the work needs a backup on the remote, will last more than a day, or another person may continue it.
Senior scenario: a teammate pushed a commit with a production database password to main an hour ago. What do you do?
Treat the password as compromised and rotate it first; that is the only step that actually fixes the exposure. Then remove the value from the code (a revert or a follow-up commit) and move it to the platform’s secret store. Decide with the team whether to rewrite history to purge it, which needs coordination because everyone must re-clone or reset, and check whether secret scanning or push protection should have blocked it and enable it if not.
Related pages
Section titled “Related pages”- Git fundamentals: working tree, index and commits explained.
- Merge, rebase and cherry-pick: interactive rebase and safe force pushes.
- Tags, hooks and commit conventions: catch mistakes before they are committed.
- Git cheatsheet