How Do I Delete a Commit From a Branch in Git

Git is a popular version control system used by developers to manage code changes.

It provides a robust way to keep track of changes made to your codebase and revert to previous versions if needed.

However, sometimes, you might end up committing changes that you would like to undo.

In such cases, removing a commit from a Git branch can come in handy.

In this article, we’ll go over the steps to remove a commit from a Git branch.


Step 1: Check the Commit History

Before removing a commit, it’s crucial to understand the commit history.

You can check the commit history of your Git branch by using the following command:

$ git log

This will show you a list of all the commits made on the branch along with their hash values, authors, and commit messages.

Step 2: Create a New Branch

To remove a commit, it’s best to create a new branch.

This ensures that your original branch remains intact, and you can always go back to it if something goes wrong.

$ git checkout -b new-branch

Step 3: Revert the Commit

To remove the commit, you need to revert it using the revert command.

The revert command creates a new commit that undoes the changes made in the previous commit.

$ git revert <commit-hash>

Replace <commit-hash> with the hash value of the commit that you want to remove.

Step 4: Push the Changes

Once you have successfully removed the commit, you need to push the changes to the remote repository.

$ git push origin new-branch

Conclusion

Removing a commit from a Git branch is a straightforward process.

By following the steps outlined in this article, you can easily undo commits and keep your codebase clean.

Remember to always create a new branch before making any changes, and to push the changes to the remote repository once you’re done.