Full Byte Developer.

The Git undo cheat sheet: pushed vs not pushed

The wrong undo command can turn a small Git slip into lost work.

Published here · 4 sources

The wrong undo command can turn a small Git slip into lost work. Ask one question first: did this commit leave my laptop?

The pushed test: pushed? revert. Not pushed? reset.

The undo commands

Each one tagged by what it can lose:

1. Staged the wrong file (safe)

bash
git restore --staged app.js

2. Committed too soon, not pushed (before push)

bash
git reset --soft HEAD~1

3. Bad commit already pushed (safe on shared branches)

bash
git revert <sha>

4. Throw away your edits (no undo)

bash
git restore app.js

5. Committed on main by mistake (only before push, with a clean git status)

bash
git branch feature
git reset --hard HEAD~1
git switch feature

Use HEAD~3 if three commits landed. reset --hard wipes uncommitted changes, so stash first.

6. Dropped a stash (rescue)

From the git stash docs:

bash
git fsck --unreachable | grep commit | cut -d\  -f3 | xargs git log --merges --no-walk --grep=WIP

Named it with -m? Remove --grep=WIP.

bash
git stash apply <sha>

Every command was run in a throwaway test repo on Git 2.54.

Send this to the friend who reached for a hard reset after a commit was already pushed.

Keep this guide

By Full Byte Developer

Filed under Dev tools

Questions about this guide

When should I use revert instead of reset?

Use revert on anything already pushed. It creates a new commit that undoes the old one without rewriting history.

How do I rescue a dropped stash?

Run git fsck to find unreachable commits, grep for WIP if you did not name it, and apply by SHA.

Sources

Next in this stack