Git & Command Line20 min readIntermediate

Undoing Things in Git

amend, reset, revert, restore, stash — every level of undo, when to use which.

I just made a typo in my last commit message

bash
git commit --amend -m "better message"
# Replaces the most recent commit. Don't do this if you've already pushed.

I forgot to add a file to my last commit

bash
git add forgotten-file.py
git commit --amend --no-edit     # adds to last commit, keeps message

I want to throw away unstaged changes

bash
git restore file.py              # for one file
git restore .                    # everything in current dir (DANGEROUS — uncommitted work lost)

I staged something I didn't mean to

bash
git restore --staged file.py     # un-stage but keep the changes
# (older syntax: git reset HEAD file.py)

I committed but want to undo the COMMIT (keep the changes)

bash
git reset --soft HEAD~1          # undo last commit; changes go back to staged
git reset HEAD~1                 # undo last commit; changes go back to working dir
git reset --hard HEAD~1          # undo last commit AND discard changes (DANGEROUS)

The commit is already pushed — I want to UNDO without rewriting history

bash
git revert abc123                # creates a NEW commit that undoes abc123
git push                          # safe to push

I have unfinished changes but need to switch branches

bash
git stash                        # set aside current changes
git switch other-branch          # do something
git switch -                     # back to original branch
git stash pop                    # bring the changes back
⚠ Watch out
`git reflog` is the safety net. Even after `git reset --hard` or a botched rebase, your old commits live in the reflog for ~90 days. If you see your work disappear, run `git reflog` first and don't panic.