Delete a commit from git

How to delete a committed change from a git repository.

It is possible that you make a commit without verifying the changes you are committing and don’t notice your error in time. Once you review the commit and notice that there is something in the commit that doesn’t belong there, how do you remove that specific commit?

To easily remove all the changes from a local git repository, use git reset --hard HEAD~

In this short post I will explain how to delete a commit in your repository and push the changes remotely.

From your git repository, first, find the commit you want to remove by looking at git log:

1
git log --pretty=oneline

Depending on position of your commit, modify the below command (below command will show the last 4 commits).

1
git rebase -i HEAD~4

This will put you in the editor. You will see something similar to:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
pick d7f8fd9 latest commit
pick 143a7bf third
pick fb0c4b4 this is second
pick 1f0e309 this is my first commit

# Rebase 9da9c9d..1f0e309 onto 9da9c9d (4 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

Delete the line that corresponds to the commit you want to delete and save the file. Check that the changes were applied correctly.

1
git log --pretty=oneline

To push this change to a remote repository, do the following (don’t forget the +):

1
git push origin +master