How to Undo Last Commit in Git: Complete Guide
How to Undo the Last Commit in Git
Making an incorrect commit in Git is a common occurrence. Fortunately, Git offers several methods to undo the last commit, depending on your needs.
1. Using git reset
-
git reset --soft HEAD~1
Removes the last commit but keeps changes in the staging area. Ideal if you want to edit the commit before pushing. -
git reset --mixed HEAD~1
Removes the last commit and unstages the changes, returning them to the working directory. -
git reset --hard HEAD~1
Completely removes the last commit and all associated changes. Use with caution as changes will be lost.
2. Using git revert
If the commit has already been pushed to a remote repository and you want to undo it without altering history:
git revert HEAD
This creates a new commit that reverses the changes from the previous commit.
3. Using Visual Studio Code
For VSCode users
-
Press
Ctrl + Shift + Gto open the Source Control panel. -
Click on the three-dot icon (more options).
-
Select "Undo Last Commit".
This will undo the last commit and return the changes to the staging area.