How to Undo the Most Recent Commit in Git? A Step-by-Step Guide

How to Undo the Most Recent Commit in Git? A Step-by-Step Guide

When working with Git, you may sometimes commit changes that you want to undo. Whether it’s a simple mistake or an unintended commit, Git provides multiple ways to revert changes. In this guide, we’ll explore different ways to undo the most recent commit, depending on your needs.

Method 1: Undo Last Commit but Keep Changes (git reset --soft)

If you want to remove the last commit but keep the changes staged, use:

git reset --soft HEAD~1

This moves the HEAD pointer one commit back, keeping your changes in the staging area.

Method 2: Undo Last Commit and Unstage Changes (git reset --mixed)

To remove the last commit and unstage the changes, use:

git reset --mixed HEAD~1

⚠️ Warning: This is irreversible, so be sure before using it!

Method 4: Undo Last Commit with git revert

If you’ve already pushed your commit and want to create a new commit that undoes the last one, use:

git revert HEAD

This creates a new commit that reverses the previous one, keeping a clean history.

Method 5: Undo Last Commit in a Branch (git restore)

For undoing only specific files from the last commit:

git restore --staged <file>

This removes the file from the staging area without deleting changes.

Which Method Should You Use?

  • Use --soft if you want to keep changes staged.

  • Use --mixed if you want to keep changes but unstage them.

  • Use --hard if you want to completely delete the commit and changes.

  • Use git revert if you’ve already pushed the commit and need a safe way to undo it.

  • Use git restore for file-specific changes.

Final Thoughts

Undoing a commit in Git is easy if you know the right commands. Always choose the method based on whether you want to keep your changes or completely erase them. Before using --hard, ensure you won’t lose any important work.