0

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?

2
  • the answer is exactly the same as in the question you quote
    – Chris Maes
    Commented Jan 26, 2017 at 16:01
  • you are right @ChrisMaes, didn't realise it, thanks
    – vaskort
    Commented Jan 26, 2017 at 16:24

3 Answers 3

2

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.

1
  • that was clean mate, thanks
    – vaskort
    Commented Jan 26, 2017 at 16:24
1
git rebase -i HEAD~6

Then in the interactive editor put squash (you can abbreviate to s) in front of the commits you want to squash and leave the others as pick.

Example:

pick 043af87 message
s    8c0fa0e message
s    b6c7116 message
pick c5d91a3 message
pick f20898f message
pick edcbad2 message
0

If you haven't published the branch, you could rewrite its history without any side effect.

Suppose the history is A-B-C-D-E-F-G-H-I and the goal is to squash C-D-E-F-G.

git checkout -b squash_branch G
git reset C --soft
git commit
git cherry-pick H I

The new history will be A-B-S-H'-I'.

Not the answer you're looking for? Browse other questions tagged or ask your own question.