11

I have a checkout copy of a remote git repository in my workstation. I have accidentally committed a change in my local and pushed to remote. Now I want to remove the last commit and go back to the previous commit and the same should be pushed to remote.

I am okay if it is a new commit with a commit message. How to do that?

Poomalairaj
  • 4,888
  • 3
  • 23
  • 27

2 Answers2

11

If nobody has yet cloned your updated remote repo, you can:

git reset --hard HEAD~
git push --force

That will force the local and remote history to discard the latest commit.
(Check first with a git fetch that no new commits had been pushed since your incorrect commit)

If a new history isn't an option, then a git revert is more secure, and will result in a new commit canceling the previous one: you can then push that new commit.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
11

I'd advise against pushing with --force an alternative history. Anyone who already pulled your changes will have a completely screwed history to deal with when pulling new stuff.

A far safer option is to simply do

git revert HEAD~1 
git push origin master

git revert will record a new commit that cancels all of the effects of the previous one

Tigraine
  • 23,358
  • 11
  • 65
  • 110
  • What does `error: your local changes to the following files would be overwritten by merge` mean? Isn't that the whole point? That I want to discard my latest commit and go back to the one previous? – mLstudent33 Aug 23 '21 at 23:55
  • 1
    That means that you probably still have changes that are not committed. This is about having a clean index (local state) and just reverting the last committed changes. – Tigraine Aug 27 '21 at 08:51