Undoing Changes: reset and revert

Use restore, reset, and revert to undo work safely depending on whether it is shared.

Git offers different tools depending on what you want to undo.

Discard uncommitted work

  • git restore file.txt — throw away changes in the working directory.
  • git restore --staged file.txt — unstage without losing edits.

Move the branch pointer with reset

  • git reset --soft HEAD~1 — undo the last commit, keep changes staged.
  • git reset --hard HEAD~1 — undo the last commit and discard its changes.

Safely undo shared commits with revert

git revert creates a new commit that reverses a previous one. It does not rewrite history, so it is safe on branches others use.

Example

Example · bash
# Undo local, unpushed work
git reset --soft HEAD~1     # keep the changes staged

# Safely undo a pushed commit
git revert a1b2c3d          # creates a new, reversing commit
git push

When to use it

  • A developer uses git revert to safely undo a merged commit on main without rewriting shared history.
  • A developer uses git reset --soft to uncommit their last three commits and re-stage them as a single clean commit.
  • A developer uses git restore to discard unsaved edits in a file and return it to the last committed state.

More examples

Revert a commit already on main

revert adds a new undo commit rather than rewriting history, making it safe to use on shared branches.

Example · bash
# Create a new commit that undoes e4a1f3c
git revert e4a1f3c
# [main 7b2c9d1] Revert "feat: add experimental feature"

Reset to uncommit local commits

--soft moves the branch pointer back but leaves all changes in the staging area ready to be recommitted.

Example · bash
# Move HEAD back 2 commits, keep changes staged
git reset --soft HEAD~2

# Re-commit as one clean commit
git commit -m "feat: unified checkout and payment flow"

Discard working directory edits

restore replaces working directory files with the version from the index (staging area) or last commit, discarding local edits.

Example · bash
# Throw away unsaved edits to one file
git restore src/app.py

# Throw away all unstaged edits
git restore .

Discussion

  • Be the first to comment on this lesson.