How to Undo Git Commits with Reset and Revert
In this tutorial, you'll learn about How to Undo Git Commits with Reset and Revert. We cover key concepts, practical examples, and best practices.
The Problem
You committed a change and need to undo it:
$ git log --oneline
3a4b5c6 (HEAD -> main) WIP: broken change
f7e8d9a Feature: user login
a1b2c3d Fix: database timeout
You cannot decide whether to use git reset or git revert, and using the wrong one can rewrite shared history or leave the branch in a messy state.
Quick Fix
Step 1: Revert if the commit is already pushed
git revert creates a new commit that undoes the changes, keeping history intact:
git revert 3a4b5c6
This opens an editor for the revert commit message. Save and exit.
Result:
$ git log --oneline
e5f6g7h (HEAD -> main) Revert "WIP: broken change"
3a4b5c6 WIP: broken change
f7e8d9a Feature: user login
Step 2: Reset if the commit is local only
git reset moves the branch pointer backward, erasing commits:
# Soft reset -- keep changes staged
git reset --soft HEAD~1
# Mixed reset -- keep changes unstaged (default)
git reset HEAD~1
# Hard reset -- discard changes entirely
git reset --hard HEAD~1
Step 3: Verify after reset
git log --oneline -3
git status
Alternative Solutions
Use git restore to unstage or discard files:
# Unstage a file
git restore --staged file.js
# Discard changes in a file
git restore file.js
Practice with a Test Repository
cd /tmp
mkdir git-practice && cd git-practice
git init --initial-branch=main
# Initialized empty Git repository in /tmp/git-practice/.git/
echo "test" > file.txt && git add . && git commit -m "init"
# [main (root-commit) abc1234] init
Before running destructive commands on your real repository, practice on a throwaway test repository. This builds confidence and prevents costly mistakes. The reflog is your safety net, but practice makes it less needed.
Additional Troubleshooting
# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"
If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.
Prevention
- Use
git revertfor commits that have been pushed to a shared branch. - Use
git reset --softfor local commits you want to redo. - Never use
git reset --hardon commits that exist on a remote. - When in doubt, use
git revert-- it is always safe.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro