Squash commits in Git

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

Often I can see following pattern: I worked hardly on implementing new feature, committed many small changes and when the feature is ready, I would like to have one solid commitment. Commits squashing helps me to get required result. So… how to do it? Let’s see example:

Well, let’s see my commits 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 5 latest commits (b50dff9 … 0b6a22b). I can do it with interactive git rebase in format git rebase -i HEAD~<N> or git rebase -i <last-requred-commit>. In my case, I have to do following command:

$> git rebase -i HEAD~5


$> git rebase -i f26798f

Git should open editor with 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 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 editor again with a proposed message for new commit. I am replacing the message with 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