To undo the last commit on GitHub, you can use the following steps based on your situation:
If You Have Not Pushed the Commit:
- Remove the Last Commit but Keep Changes:
bash
git reset --soft HEAD~1
This will undo the last commit and leave your changes staged for a new commit.
- Remove the Last Commit and Discard Changes:
bash
git reset --hard HEAD~1
This completely removes the last commit and any changes made in it.
If You Have Already Pushed the Commit:
- Undo Locally and Force Push:
If the commit has been pushed, usegit reset
followed by a force push:bashgit reset --hard HEAD~1
git push origin main --force
Note: Force-pushing can overwrite others’ work if they have also made changes. Use it cautiously.
- Revert the Commit (Safe for Shared Repositories):
If others might have pulled the changes, create a new commit to undo the changes:bashgit revert HEAD
This creates a new commit that reverses the last commit’s changes.
Choose the method based on whether you’ve pushed the commit and whether others are collaborating on the branch.