Search code examples
gitgit-squash

How to squash the latest commit into a specific commit (which is not the previous commit)?


Suppose I am trying to rebase my current branch which has changes on top of master :-


And am presented with an interactive window like this with all the new commits listed:

pick A Commit message A
pick B Commit message B
pick C Commit message C
pick D Commit message D
pick E Commit message E

And I want to squash E to C and not to the previous commit D. Is there a way to do that?

Coz If I do this

pick A Commit message A
pick B Commit message B
pick C Commit message C
pick D Commit message D
squash E Commit message E

it will always squash E to D but I want to squash E into some previous commit that I can choose like C or B or A.


Solution

  • You can reorder the lines in the "interactive window" any way you wish and rebasing will reorder the corresponding commits. For example, you can move the line for commit C so it is above the line for commit E:

    pick A Commit message A
    pick B Commit message B
    pick D Commit message D
    pick C Commit message C
    squash E Commit message E
    

    Now the resulting history will have the changes from commits A, B, and D in that order, then a new commit with the changes from commits C and E squashed into a single commit.

    Or, move the line for commit E so it is below the line for commit C:

    pick A Commit message A
    pick B Commit message B
    pick C Commit message C
    squash E Commit message E
    pick D Commit message D
    

    This will keep the changes from commits A and B in that order, then create a new commit with the combined changes of C and E, and finally a new commit with the same changes as D.