How To Delete A Git Commit

How to use git reset, git revert, and git rebase to delete a commit in Git.

TL;DR

Use git reset, git revert or git rebase -i to delete a commit in Git.

Written by @bazamel_

Image cover

There are a few ways to delete a commit in Git, depending on the specific situation.

Using git reset

The git reset command can be used to remove commits from the current branch. You can use the HEAD~n notation to specify the number of commits to remove, where n is the number of commits to go back. For example, to remove the last commit, you can use the command:

git reset HEAD~1

This will remove the last commit, but keep the changes in the working directory, so you can make any necessary modifications and commit the changes again.

It’s important to note that using git reset will change the commit history permanently, so it’s a good practice to make sure that you have a backup of the code before using it.

Using git revert

Another way to delete a commit is by using the git revert command. This command creates a new commit that undoes the changes made in a previous commit. For example, to revert the last commit, you can use the command:

git revert HEAD

This command will create a new commit that undoes the changes made in the last commit, but keeps the commit history intact.

It’s important to note that git revert is a safer option than git reset because it doesn’t change the commit history permanently and can be easily undone.

Using git rebase -i

You can also use the git rebase -i command to delete a commit. This command allows you to interactively edit the commit history, including deleting commits.

For example, to delete the last commit, you can use the command:

git rebase -i HEAD~1

This command will open the default text editor, showing the list of commits in reverse chronological order, where you can change the word pick on the line of the commit you want to delete to drop.

It’s important to note that git rebase -i also changes the commit history permanently, so it’s a good practice to make sure that you have a backup of the code before using it and also it’s recommended to use it on a branch that hasn’t been pushed yet, because once you’ve pushed the branch it is more complex to change it.