Search code examples
gitsquashgit-squash

How to squash your commits when not being your recent ones


It seemed easy to squash your commits if these are your recent ones (Squash my last X commits together using Git)

But what if I want to squash a few commits of my repo that are not the recent ones, say HEAD~3 to HEAD~6.

Is there a way to do this?


Solution

  • This can be done by doing an interactive rebase.

    If you have branch master at commit A, and then you created branch my-branch with commits B, C, D, E, and F. You want to squash commits B, C, and D into B'.

    Make sure your current branch is my-branch, and start an interactive rebase:

    git rebase -i master
    

    This will open your editor with the list of commits that will be acted upon. Each line represents one commit, and the first word on that line says the command to perform on that commit. Leave the first commit (B) as pick, and change the commands for the next two commits (C and D) to squash. Save and close the editor.

    After git has finished processing commits B, C, and D, a new editor will open with a commit message for the new commit B'. This will contain a combination of the commit messages from the original commits, but you can change it to whatever you'd like. Once the commit message is what you want it to be, save and close the editor.

    Once git has finished processing the rest of the commits on branch my-branch, commits on my-branch will be B', E, and F.

    Note that you should only do a rebase if you haven't pushed your commits. Rebasing will change the hashes of your commits, which will cause problems if someone else has already pulled the original commits.