2

Okay I am new to Git and would like to know how to remove a commit before the HEAD. For instance-:

commit foo (This is the HEAD)

commit bar (This is what I want to remove)

How do I delete commit bar entirely from this branch but keep commit foo?

Koraktor
  • 41,357
  • 10
  • 69
  • 99
Kramer786
  • 1,238
  • 1
  • 12
  • 26

2 Answers2

6

git rebase -i HEAD~2

Will let you interactivly remove the commit

git rebase will remove all reference of that commit and change the id of the HEAD commit. Meaning people MAY have issues if they have branched from the old commit

git revert <commitID>

may be a better way to keep history

exussum
  • 18,275
  • 8
  • 32
  • 65
  • The revert option is far superior if you are sharing that branch with others – Jonathan.Brink Sep 05 '15 at 20:09
  • Instead of looking up the commit’s ID (e.g. using `git log`), you can also use `HEAD^` or `HEAD~1` for "the commit before HEAD". – Koraktor Sep 05 '15 at 20:31
  • I would always use log to confirm the sha1 to confirm – exussum Sep 05 '15 at 20:33
  • Okay none of the given commands work. `git rebase` gives the error of `invalid upstream HEAD~2`. And `git revert` creates an extra commit but does not delete the commit that I want from the log. What I want to do is delete only the first commit made and not the recent one. – Kramer786 Sep 06 '15 at 09:27
  • Okay solved it. It seems you cannot remove the first commit you can only edit it. So I deleted the commits before the first one and edited the first commit accordingly. Refer [link](http://stackoverflow.com/questions/10911317/how-to-remove-the-first-commit-in-git) for details. – Kramer786 Sep 06 '15 at 09:38
0

Another option is to checkout a new branch at the commit previous to the commit that you want to delete:

git checkout -b new_branch HEAD~2

And then to cherry pick the commits from the other branch to the new branch:

git cherry-pick <hash of the other branch's HEAD>

The graph would then look like this:

* 6a59727 (HEAD, new_branch) foo
| * 15f07fd (master) foo
| * 6bba064 bar
|/  
* dec804e baz
sergej
  • 17,147
  • 6
  • 52
  • 89