0

git log scenario:

Commit 1

Commit 2

Commit 3

Commit 4

Commit 5

Commit 6

I need to remove commits 2-4 from between making the final git log as

Commit 1

Commit 5

Commit 6

What is the best way to do it?

adimoh
  • 658
  • 2
  • 8
  • 20
  • 1
    You could do this with an [interactive git rebase](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History#_changing_multiple). – larsks May 10 '18 at 12:50
  • 4
    Possible duplicate of [Remove specific commit](https://stackoverflow.com/questions/2938301/remove-specific-commit) – Miko May 10 '18 at 12:50

1 Answers1

5

This is what rebasing is for: changing the history of a commit.

Note: rebasing or any other operation changing the history of a commit will change the commit hash of every commit, so the histories are incompatible with each other and you cannot git push commits with a modified history if any of the changed commits have already been pushed. You should only do this for changes you have made locally, but not pushed yet.

If your Git log looks something like this to begin with:

4e4c39d   Commit 1
fbdb7a2   Commit 2
f32770f   Commit 3
de3f6dd   Commit 4
942266a   Commit 5
a7e80a4   Commit 6

Then you can run git rebase -i 434c39d (where 434c39d is the oldest commit you don't want to change, in this case Commit 1). This will open an editor with a list of all the commits:

pick 4e4c39d Commit 1
pick fbdb7a2 Commit 2
pick f32770f Commit 3
pick de3f6dd Commit 4
pick 942266a Commit 5
pick a7e80a4 Commit 6

You can change pick for each commit to change how it will be changed: fixup and squash will remove the commit but keep the changes (they're merged into the previous commit), while drop will remove the commit and the changes in it. Then save, close the editor and git will rebase and apply the changes you specified to the Git history.

In your example, if you want to remove the commits but keep the changes, for example, you could do

pick  4e4c39d Commit 1
fixup fbdb7a2 Commit 2
fixup f32770f Commit 3
fixup de3f6dd Commit 4
pick  942266a Commit 5
pick  a7e80a4 Commit 6

If you don't want to keep the changes from these commits, you could change fixup to drop instead.

Frxstrem
  • 38,761
  • 9
  • 79
  • 119