🔧 Error Fixes
· 1 min read

How to Undo the Last Git Commit


# You just committed something wrong and need to undo it

There are several ways to undo a commit depending on whether you’ve pushed it and whether you want to keep the changes.

Fix 1: Undo Commit, Keep Changes (Most Common)

# Undo last commit, keep files staged
git reset --soft HEAD~1

# Undo last commit, unstage files (keep changes in working directory)
git reset HEAD~1
# Same as: git reset --mixed HEAD~1

Fix 2: Undo Commit, Discard Changes

# ⚠️ Permanently deletes the changes
git reset --hard HEAD~1

Fix 3: Amend the Last Commit

# Fix the commit message
git commit --amend -m "New message"

# Add forgotten files to the last commit
git add forgotten-file.js
git commit --amend --no-edit

Fix 4: Already Pushed — Use Revert

# ✅ Safe for shared branches — creates a new "undo" commit
git revert HEAD
git push

# This doesn't delete history — it adds a new commit that undoes the previous one

Fix 5: Undo Multiple Commits

# Undo last 3 commits, keep changes
git reset HEAD~3

# Revert multiple pushed commits
git revert HEAD~3..HEAD

Fix 6: Find a Lost Commit

# If you accidentally reset too far
git reflog
# Find the commit hash you want
git reset --hard abc1234

Quick Reference

ScenarioCommand
Undo commit, keep changes stagedgit reset --soft HEAD~1
Undo commit, keep changes unstagedgit reset HEAD~1
Undo commit, delete changesgit reset --hard HEAD~1
Fix last commit messagegit commit --amend
Undo pushed commitgit revert HEAD

Related: Fix: fatal: not a git repository

📘