0

Let's say I have the following commits:

E (HEAD -> dev, origin/dev)
|
D
|
C
|
B
|
A

Now I want to remove or skip commit B, so that it looks like this:

E (HEAD -> dev, origin/dev)
|
D
|
C
|
A

Can I do git checkout C then git rebase A? Will that get the intended result.

  • 3
    `git rebase -i HEAD~4`, then `drop` the commit you want to skip? Or you could `revert` it, to avoid rewriting history. – jonrsharpe Jan 06 '21 at 09:19
  • 1
    Does this answer your question? [Delete commits from a branch in Git](https://stackoverflow.com/questions/1338728/delete-commits-from-a-branch-in-git) – CodeCaster Jan 06 '21 at 09:28

1 Answers1

1

I couldn't find an exact duplicate of your question, so I am venturing an answer. The tool you want here is an interactive rebase. Run the following, from the HEAD of your current branch:

git rebase -i HEAD~5

This should bring up a screen showing the most recent 5 commits, looking something like this (oldest commit first to newest commit last):

pick <SHA-1 for A> commit message for A
pick <SHA-1 for B> commit message for B
pick <SHA-1 for C> commit message for C
pick <SHA-1 for D> commit message for D
pick <SHA-1 for E> commit message for E

To remove the B commit, all you have to do is to delete the pick line for the B commit. So do that from your editor, leaving you with this:

pick <SHA-1 for A> commit message for A
pick <SHA-1 for C> commit message for C
pick <SHA-1 for D> commit message for D
pick <SHA-1 for E> commit message for E

Now save and close the editor. Git should automatically start the rebase, which in this case will mean replaying the C and A commits on top of the new base, which is the D commit. You may get merge conflicts along the way, and you would have to resolve them.

Note that the operation you are doing is not very history friendly, and you should avoid rewriting history in this way if your branch is already being used by other people.

Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263