Pablo Jurado

12 August, 2020

How to delete commits from Git

Sometimes we need to delete committed code from Git. We are going to explore the different approaches.

How to delete the last commit

When working locally in our branch, if we want to delete the last commit, we can run the following command

git reset --hard HEAD^

Always be careful when running reset --hard because this will delete our code from the git history.

If we want to keep the code, we can run

git reset --soft HEAD^

This will delete the commit but keep the code.

How to edit some code from the last commit

Sometimes we don't want to delete the commit, but we need to cleanup leftover code, fix a typo or change the commit message. We can update our files and then run

git --amend

This will add the changes to current commit. Also, we will be prompted to update the current commit message.

How to delete several commits

When trying to delete older commits we can use rebase. For example this command will show the last 4 commits

$ git rebase -i HEAD~4
pick f7f3f6d update css styles for the home page
pick 310154e Update README
pick a5x3b5d install css icons
pick 4af4a0d delete old tests

From that list of 4 commits we can delete the one we don't want. As you can see, the interactive rebase has many other options and can be a very powerful tool.

How to delete a commit that was pushed to a remote branch

Lastly, if our code has been merged to a remote branch and other developers are using it. The previous options are not ideal, because they will change the Git history and the main branch will be out of sync.

For that case we can run

git revert <commit hash here>

This will create a new commit with the changes needed to revert the original code.

Main take away

Is always recommended to commit often. We want our commits to be focus on a small feature or functionality. The commit message should be concise and descriptive.

If we follow this rules, deleting and searching commits should be straight forward.