Skip to content

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.

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

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.

Terminal window
git restore --staged refund.txt # unstage, keep the edit
git restore refund.txt # discard the edit
git restore . # discard every unstaged edit in the tree

Pitfalls:

  • Discarded edits are gone. git restore <path> and git restore . delete uncommitted work that Git never stored. If in doubt, git stash first.
  • restore does not touch untracked files. New files you never added stay put; use git clean for those.

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.

Terminal window
git add invoice.txt
git commit -m "Add invocie"
# notice the typo and a missing change
git add invoice.txt
git commit --amend -m "Add invoice export"
git log --oneline -2

Output:

086fb97 Add invoice export
2dfbf30 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> and git rebase -i --autosquash, described in Merge, rebase and cherry-pick.

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.

Terminal window
git revert --no-edit HEAD
git log --oneline

Output:

[main 2dfbf30] Revert "Automate refunds"
1 file changed, 1 insertion(+), 1 deletion(-)
2dfbf30 Revert "Automate refunds"
d7ea637 Automate refunds
276b1e9 Add refund flow
6df936e Add order status

Pitfalls:

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

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:

  • --soft keeps 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.
  • --hard discards them from the index and the working tree.
Terminal window
git reset --soft HEAD~1; git status --short
git commit -q -m "Automate refunds"
git reset HEAD~1; git status --short
git commit -qam "Automate refunds"
git reset --hard HEAD~1; git status --short; cat refund.txt

Output:

M refund.txt
Unstaged changes after reset:
M refund.txt
M refund.txt
HEAD is now at 276b1e9 Add refund flow
refund = manual

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

  • --hard also 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 main and force pushing removes commits from everyone’s history. Use revert on shared branches.
  • git reset --hard origin/main is a sledgehammer. It makes your branch match the remote exactly and throws away local commits and edits; run git status and git log origin/main.. first.

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.

Terminal window
git reflog -4
git reset --hard HEAD@{1}
cat refund.txt

Output:

276b1e9 HEAD@{0}: reset: moving to HEAD~1
d7ea637 HEAD@{1}: commit: Automate refunds
276b1e9 HEAD@{2}: reset: moving to HEAD~1
d7ea637 HEAD@{3}: commit: Automate refunds
HEAD is now at d7ea637 Automate refunds
refund = automatic

Creating 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 gc expires entries after 90 days, and after 30 days for entries no longer reachable from a branch tip (gc.reflogExpire and gc.reflogExpireUnreachable).
  • Each branch has its own reflog too. git reflog show feature/discounts shows where that branch pointed, which helps after a bad rebase.

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.

Terminal window
git stash push -u -m "WIP: dashboard filters"
git stash list
git stash show --include-untracked stash@{0}
git switch main # fix the urgent bug, commit, come back
git switch feature/dashboard-filters
git stash pop

Output (abridged):

Saved working directory and index state On feature/dashboard-filters: WIP: dashboard filters
stash@{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.txt
The 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 plain git stash leaves 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 -m and 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. Prefer apply plus a deliberate drop for anything valuable.

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.

Terminal window
git clean -n # preview
git clean -fd # delete untracked files and directories
git rm --cached appsettings.Local.json
echo "appsettings.Local.json" >> .gitignore
git 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 -x removes ignored files. That includes .env files and local databases; read the -n output.
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 "..."

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.