Squash commits in Git

Nov 4, 2019 00:00 · 290 words · 2 minutes read Git Developer

Often I can see the following pattern: I worked hard on a new feature, committed many small changes and when the feature is ready, I would like to have one solid commit. Squashing commits gets me the result I want. So… how to do it? Let’s see an example:

Well, let’s see my commit history:

$> git log --oneline
0b6a22b (HEAD -> master) Added unit tests
0bde9e4 Example, example, example
dd2b136 Added design info
9d50b03 Small change 2
b50dff9 Small change 1
f26798f Initial commit

I would like to squash the last 5 commits (b50dff9 … 0b6a22b). I can do it with an interactive git rebase in the format git rebase -i HEAD~<N> or git rebase -i <last-required-commit>. In my case, I have to run the following command:

$> git rebase -i HEAD~5

or

$> git rebase -i f26798f

Git should open an editor with the following content:

pick b50dff9 Small change 1
pick 9d50b03 Small change 2
pick dd2b136 Added design info
pick 0bde9e4 Example, example, example
pick 0b6a22b Added unit tests

What I should do - just mark the first commit as p(ick) and all other commits as s(quash):

p b50dff9 Small change 1
s 9d50b03 Small change 2
s dd2b136 Added design info
s 0bde9e4 Example, example, example
s 0b6a22b Added unit tests

Save, quit from the editor and… git should open the editor again with a proposed message for the new commit. I am replacing the message with a simple “Prepared pre-release” and again - save, quit from the editor.

Voilà! We have squashed commits.

$> git log --oneline
811b769 (HEAD -> master) Prepared pre-release
f26798f Initial commit

For more information about git rebase click here.

Also read about Squash and merge from GitHub click here.