🛠️ ITBlogs.pro

Git Undo Cheat Sheet: Fix Almost Any Mistake

Oct 16, 2026 · Git · 3 min read

Everyone makes Git mistakes. Almost all of them are recoverable, if you know which command fits. Find your situation below.

Safety net first: almost nothing in Git is truly lost for a while. git reflog records every place HEAD has been. See the last section.

Undo changes in your working directory

Discard edits to one file (⚠️ this cannot be undone):

git restore path/to/file

Unstage a file you git add-ed, keeping the edits:

git restore --staged path/to/file

Throw away all local changes:

git restore .
git clean -fd          # also delete untracked files/dirs (check first with -n)

Fix the last commit (not pushed yet)

Wrong message, or forgot a file:

git add forgotten-file
git commit --amend            # opens editor; or add -m "new message"

Undo the commit but keep the changes staged:

git reset --soft HEAD~1

Undo the commit and keep the changes unstaged:

git reset HEAD~1              # same as --mixed

Undo the commit and destroy the changes:

git reset --hard HEAD~1

Undo something that is already pushed

Never rewrite shared history. Add a new commit that cancels the old one:

git revert <commit-sha>
git push

For a merge commit you need to pick the parent to keep:

git revert -m 1 <merge-sha>

If you really must rewrite a branch only you use:

git push --force-with-lease     # refuses if someone else pushed in the meantime

Prefer this over plain --force.

Committed on the wrong branch

git switch -c correct-branch    # new branch at the current commit
git switch wrong-branch
git reset --hard HEAD~1         # remove the commit from the wrong branch

Or move a single commit with cherry-pick:

git switch correct-branch
git cherry-pick <sha>

Undo a merge or rebase

git merge --abort
git rebase --abort

Already completed the merge locally and not pushed:

git reset --hard ORIG_HEAD

"I deleted a branch" / "I lost commits"

git reflog

You'll see lines like a1b2c3d HEAD@{3}: commit: add login page. Bring it back:

git branch rescued a1b2c3d
# or move the current branch back there
git reset --hard HEAD@{3}

Reflog entries last about 90 days by default, so don't panic, but act soon.

Remove a file from Git but keep it on disk

Handy when you committed something that belongs in .gitignore:

git rm --cached path/to/file
echo "path/to/file" >> .gitignore
git commit -m "Stop tracking file"

I committed a password or API key

  1. Rotate the secret immediately. Assume it is already compromised.
  2. Then remove it from history with git filter-repo and force-push. Deleting it in a new commit is not enough, as it stays in history.

Cheat sheet

I want to… Command
Discard file edits git restore file
Unstage git restore --staged file
Edit last commit git commit --amend
Undo commit, keep changes git reset --soft HEAD~1
Undo commit, lose changes git reset --hard HEAD~1
Undo pushed commit git revert <sha>
Find lost commits git reflog