0
0
GitHow-ToBeginner · 3 min read

How to Undo Last Commit in Git: Simple Commands Explained

To undo the last commit in Git, use git reset --soft HEAD~1 to keep changes staged or git reset --hard HEAD~1 to discard changes. Alternatively, use git revert HEAD to create a new commit that undoes the last one without changing history.
📐

Syntax

Here are the main commands to undo the last commit in Git:

  • git reset --soft HEAD~1: Undo last commit but keep changes staged.
  • git reset --hard HEAD~1: Undo last commit and discard all changes.
  • git revert HEAD: Create a new commit that reverses the last commit.
bash
git reset --soft HEAD~1
git reset --hard HEAD~1
git revert HEAD
💻

Example

This example shows how to undo the last commit while keeping your changes staged using git reset --soft HEAD~1. It also shows how to undo and discard changes with git reset --hard HEAD~1, and how to undo with a new commit using git revert HEAD.

bash
# Check current commit history
git log --oneline -1

# Undo last commit but keep changes staged
git reset --soft HEAD~1

# Undo last commit and discard changes
git reset --hard HEAD~1

# Undo last commit by creating a new commit
git revert HEAD
⚠️

Common Pitfalls

Be careful when using git reset --hard because it deletes changes permanently. If you already pushed the commit to a shared repository, git reset can cause problems for others. In that case, prefer git revert which safely undoes changes by adding a new commit.

Also, HEAD~1 means the commit before the last one. Using the wrong number can undo more commits than intended.

bash
git reset --hard HEAD~1  # Dangerous if you have uncommitted work

git revert HEAD           # Safer for shared repos
📊

Quick Reference

CommandEffectUse Case
git reset --soft HEAD~1Undo last commit, keep changes stagedFix last commit message or add more changes
git reset --hard HEAD~1Undo last commit and discard changesRemove last commit and all changes permanently
git revert HEADCreate new commit that undoes last commitUndo changes safely in shared repos

Key Takeaways

Use git reset --soft HEAD~1 to undo last commit but keep your changes staged.
Use git reset --hard HEAD~1 to undo last commit and discard all changes permanently.
Use git revert HEAD to safely undo last commit by creating a new commit.
Avoid git reset --hard if you have uncommitted work or shared commits.
Always double-check which commit you are undoing with HEAD~1.