It deletes the last commit (i.e., the last SHA) in GitHub, but it involves rewriting the commit history and requires using a force push.
Steps to Delete the Last Commit from GitHub:
1. Reset Your Local Repository
To delete the last commit, you can use git reset. If you want to completely remove the commit (including changes), you can perform a hard reset:
git reset --hard HEAD~1--hard: This will remove the commit and the changes from your working directory and staging area.HEAD~1: This means "go back 1 commit" (i.e., remove the last commit).
If you just want to keep the changes in your working directory (without deleting them completely), you can use
--softor--mixedinstead of--hard:
--soft HEAD~1: Keeps the changes in the staging area.
--mixed HEAD~1: Keeps the changes in your working directory but removes them from the staging area.
2. Force Push the Changes to GitHub
After performing the reset locally, you need to force-push the changes to overwrite the commit on GitHub:
git push --forceThis will remove the last commit from both your local repository and GitHub. Be careful with this, as it rewrites history.
Things to Consider:
- Force-pushing is generally safe when you're working alone, as no one else is depending on the commit history. However, if you were working in a team, force-pushing could overwrite changes others might have based their work on.
- The commit will be permanently removed from the history on GitHub, unless someone else has already pulled it (in which case, they might still have the commit locally).
- Safety: If you're uncertain, you can make a backup branch before doing the reset:
git branch backup-branchThis way, if anything goes wrong, you can always go back to backup-branch.
Summary:
- Run
git reset --hard HEAD~1to remove the last commit locally. - Use
git push --forceto remove the commit from GitHub.
That’s it! The last commit will be deleted both locally and remotely.