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.
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.
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!
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.
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.
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.
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.