Winston
Winston

Reputation: 1428

Git: How to remove one commit from the main branch

I currently have one git branch and it is a flat git repo. I would like to remove one commit (not the latest one). May I know how to get this done?

I found what I wanna do is very similar to the picture below.

enter image description here

Upvotes: 1

Views: 160

Answers (4)

Shane Thomas
Shane Thomas

Reputation: 15

You can just type "git log" and find the commitSHA of the commit which you want to remove.

Then type,

git revert commitSHA

      Or

git revert -n commitSHA, if you just want to revert that only modifies the working tree and the index.

Also, you can use git revert HEAD, inorder to revert the recent commit you had done.

Upvotes: 0

Romain Valeri
Romain Valeri

Reputation: 21938

A possible alternative to removing the commit

If you want or need to keep history straight, add a new commit on top whose job is to negate everything your bad commit (X) has brought. This operation is called "revert" in git lingo.

git revert HEAD~2

would work in the case you're in, but you can also, rather than pointing to the commit relatively, do a git log, spot the bad commit, store its hash, and use it

git revert <commit-SHA1>

Afterwards, your tree will look like this

A---X---C'---D'---Y

where Y contains the exact inverse changes compared to X. So the resulting codebase will be "as if you never did commit X", with the advantage of keeping track of the (canceled) operation.

Upvotes: 2

manojlds
manojlds

Reputation: 301147

Do:

git rebase -i HEAD~3

In the interactive editor, remove the line for the commit you want to remove and complete the interactive rebase operation (save and exit from the editor.)

Upvotes: 1

Ry-
Ry-

Reputation: 224913

There are single commands you can use, but one easy way is:

  • git stash (if you don’t have a clean working directory)
  • git rebase -i A
  • delete the pick X line in your text editor, save, and quit

Upvotes: 1

Related Questions