How to use `git revert` for a Safer Alternative In GIT
If the commit has already been pushed to a shared repository, a safer approach is to use `git revert`. This command creates a new commit that undoes the changes of a specified commit without rewriting history.
To revert a specific commit:
git revert <commit_hash>
Replace `<commit_hash>` with the hash of the commit you want to revert. This creates a new commit that reverses the changes, preserving the commit history.
Example Scenario
Let’s say you want to delete the most recent commit:
- Run:
git reset --hard HEAD~1
- If the commit was pushed to the remote repository, force push the changes:
git push origin main --force
For deleting an older commit, assuming the last 3 commits:
- Run:
git rebase -i HEAD~3
- In the editor, delete the line corresponding to the commit you want to remove.
- Save and close the editor.
- Force push the changes:
git push origin main --force
How to Delete Commit in Git?
Deleting a commit in Git can be done in several ways, depending on whether the commit is local or has already been pushed to a remote repository. Here’s an article on how to delete a commit in Git, covering both recent and older commits, as well as considerations for working with remote repositories.