Chapter 6 · Lesson 4 of 10
Git for deployers

Undo mistakes in Git: restore, amend, reset, revert, reflog

To undo something in Git, pick the tool by where the mistake is: restore for files, commit --amend for the last commit, reset for local history, revert for shared history and reflog to recover.

By the end you will

Choose the right undo command for a file edit, a staged file, a bad commit or a pushed commit, and recover work you thought was lost.

Time
20 min
Level
Intermediate
Check
4 questions
You need
  • A repository with a few commits

Git has a different undo for each layer. Use git restore for file edits and unstaging, git commit --amend to fix the last commit, git reset to move local history back, and git revert to cancel a commit that is already shared. When something seems lost, git reflog usually finds it. The danger is git reset --hard, which discards uncommitted work for good.

How it works#

Recall the three areas from the first repository lesson: working tree, staging area, repository. A mistake lives in one of them, and each undo command targets one.

A branch is a label pointing at a commit, and HEAD is a label pointing at your current branch (usually). HEAD~1 means one commit before HEAD. Reset moves the branch label, which is why it can make commits disappear from the log. Git does not delete those commits right away. They stay in the object database until garbage collection removes unreferenced ones after a grace period, and the reflog still lists them until then.

Decision table#

SituationCommandSafe on shared history?
Discard edits to a filegit restore filen/a, local only. Destroys the edits
Unstage a file, keep editsgit restore --staged fileYes
Fix the message or contents of the last commitgit commit --amendNo if already pushed
Undo last commit, keep changes stagedgit reset --soft HEAD~1No if already pushed
Undo last commit, keep changes unstagedgit reset --mixed HEAD~1No if already pushed
Undo commits and discard the changesgit reset --hard HEAD~1No. Destructive
Cancel a pushed commitgit revert <hash>Yes
Recover a lost commitgit reflog, then git reset or git switch -cYes, local

Step 1: Discard or unstage file changes#

bash
git restore README.md             # throw away unstaged edits to README.md
git restore --staged README.md    # unstage, keep the edits

Warning: git restore file has no undo. The edits are not in any commit, so Git cannot get them back. Run git diff file first if you are not sure.

Step 2: Fix the last commit with amend#

You forgot a file or made a typo in the message:

bash
git add forgotten.txt
git commit --amend -m "add health check endpoint"

Amend replaces the last commit with a new one, so its hash changes. That is fine locally. If you already pushed it, amending means rewriting shared history, so avoid it or coordinate first.

Step 3: Move local history with reset#

All three modes move the branch back. They differ in what happens to your changes:

bash
git reset --soft HEAD~1    # branch moves, changes stay STAGED
git reset --mixed HEAD~1   # branch moves, changes stay in the working tree, unstaged (default)
git reset --hard HEAD~1    # branch moves, changes are DISCARDED

Use --soft to squash a few commits into one (git reset --soft HEAD~3, then commit again). Use --mixed to re-split a commit.

Strong warning about --hard: it overwrites your working tree and staging area with the target commit. Uncommitted work is deleted with no recovery. Before running it, run git status and git stash or commit to a throwaway branch if anything matters. Never run it on a server copy that holds hand edits you have not saved elsewhere. See also the safe file handling lesson for the same habit with rm.

Step 4: Undo shared history with revert#

If other people (or your servers) already pulled the commit, do not rewrite history:

bash
git revert a1b2c3d
git push

Revert creates a new commit with the opposite changes. History keeps both the original and the cancellation, which is honest and safe. For a merge commit you must pick the parent: git revert -m 1 <merge-hash>.

Step 5: Recover with reflog#

bash
git reflog

Each line shows an entry such as a1b2c3d HEAD@{2}: commit: add login page. Find the state you want, then either move back to it or save it on a branch:

bash
git branch rescue a1b2c3d
git reset --hard a1b2c3d

Creating a rescue branch first is the safest, since it only adds a label. The reflog is local to your clone and entries expire after a period, so recover soon.

A tidy history also makes a rollback of a deploy simple. If a leaked secret is the mistake, rotate it first (see gitignore and secrets). The blog post Roll back a failed Docker deploy covers the deploy side.

Check it worked#

After any undo, run git status and git log --oneline -5. Confirm the branch points where you expect and the working tree is what you want. After a revert, the log shows a new Revert "..." commit on top.

Edge cases and gotchas#

  • Uncommitted work is not in the reflog. The reflog tracks commits. Edits you never committed or stashed cannot be recovered after --hard or restore.
  • Amend and reset rewrite history. After either, a plain git push is rejected if the old commit was pushed. Resist force pushing on a shared branch.
  • git clean deletes untracked files. It is separate from reset. Preview with git clean -n before git clean -f.
  • HEAD~1 and HEAD^ mean the same here. For merge commits they differ, because a merge has more than one parent.
  • Revert can conflict. If later commits touched the same lines, you resolve it like a normal merge conflict.
  • Stash is the quick parking spot. git stash push -m "wip" saves uncommitted edits and cleans the tree, git stash pop brings them back.

Troubleshooting#

SymptomLikely causeFix
error: pathspec 'file' did not match any file(s) known to gitWrong path or the file is untrackedCheck git status and the spelling
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working treeThe repository has only one commitFix the first commit with git commit --amend instead of resetting
! [rejected] main -> main (non-fast-forward) after amend or resetYou rewrote a pushed commitUse git revert instead, or coordinate a careful force push
error: Your local changes to the following files would be overwritten by checkoutEdits conflict with the targetCommit, stash or restore them first
error: commit a1b2c3d is a merge but no -m option was given.Reverting a merge commitUse git revert -m 1 a1b2c3d
git reflog is empty or missing the commitDifferent clone, or the entry expiredCheck another clone, or the remote with git fetch
fatal: bad revision 'a1b2c3d'Typo in the hash, or the commit was garbage collectedRe-read git reflog, copy the hash again

Quick reference#

bash
git restore file                  # discard edits (destructive)
git restore --staged file         # unstage
git commit --amend                # fix the last commit (unpushed only)
git reset --soft HEAD~1           # undo commit, keep staged
git reset --mixed HEAD~1          # undo commit, keep unstaged
git reset --hard HEAD~1           # undo commit AND discard changes
git revert <hash>                 # cancel a pushed commit
git reflog                        # find lost commits
git branch rescue <hash>          # save a lost commit

Next#

Keep your experiments isolated with Git branches and merging.

Check what you learned4 questions
1You staged a file by mistake and want it out of the next commit, keeping your edits. Which command?
2A bad commit is already pushed and others pulled it. What is the safe fix?
3Which reset mode throws away uncommitted changes in your working tree?
4You ran git reset --hard and lost a commit. Where do you look for its hash?

Frequently asked questions

How do I undo the last commit in Git?

If you have not pushed it, run git reset --soft HEAD~1 to keep the changes staged, or git commit --amend to fix it. If it is already pushed, use git revert HEAD to add a new commit that cancels it.

What is the difference between git reset and git revert?

reset moves the branch pointer back and rewrites local history. revert adds a new commit that reverses an earlier one, so shared history stays intact.

Can I recover a commit after git reset --hard?

Often yes. Run git reflog to find the commit hash from before the reset, then git reset --hard <hash>. This only works for committed work, not for uncommitted edits that --hard discarded.

How do I unstage a file in Git?

Run git restore --staged <file>. The file stays modified in your working tree but leaves the staging area.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios