482

How can I remove the last commit from a remote Git repository such as I don't see it any more in the log?

If for example git log gives me the following commit history

A->B->C->D[HEAD, ORIGIN]

how can I go to

A->B->C[HEAD,ORIGIN]
knittl
  • 246,190
  • 53
  • 318
  • 364
user1059540
  • 4,823
  • 3
  • 14
  • 4

2 Answers2

1164

Be aware that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:

git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit

If you want to still have it in your local repository and only remove it from the remote, then you can use:

git push origin +HEAD^:$name_of_your_branch # e.g. +HEAD^:master

Some shells interpret the ^ character. For those shells, either quote/escape or use ~:

HEAD\^
'HEAD^'
HEAD~
knittl
  • 246,190
  • 53
  • 318
  • 364
  • 37
    Just a note, in zsh use `git reset HEAD\^` – Alter Lagos Apr 10 '14 at 04:38
  • 56
    Use `git reset HEAD~1` on Win machines – æ-ra-code Apr 10 '14 at 13:43
  • 3
    what does +HEAD do? When I did `git log` it added `(HEAD -> approval, origin/approval)` on the latest commit. what does that mean? – ASN Oct 03 '17 at 02:22
  • 3
    @ASN: it force-pushes the currently checked out branch (which was/is `approval` in your case). – knittl Oct 03 '17 at 05:46
  • How to handle 'alternate reality' on other's PC – Usman Aug 12 '20 at 11:06
  • To maintain the deleted commit changes locally add the `--soft ` flag, `git reset HEAD^ --soft` – Ikbel Dec 10 '20 at 10:50
  • It is possible that the permission on your remote repo branch does not allow the "ForcePush". To get around that use the information here: https://stackoverflow.com/questions/46213673/how-do-i-grant-git-forcepush-permissions-for-pushing-bfg-repo-cleaner-results – Ryan Naccarato Nov 26 '21 at 21:41
  • In my case, I wanted to remove a commit starting at a specific hash. Then I used `git push origin hash:branch -f` to do so. – testing_22 Dec 19 '21 at 05:12
28

If nobody has pulled it, you can probably do something like

git push remote +branch^1:remotebranch

which will forcibly update the remote branch to the last but one commit of your branch.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173