Git | How to squash commits into one

In Git you have the possibility to squash commits. This is really useful to have a clean log-tree. If your process involves a code reviewer your commit isn’t split into several pieces of code snippets, because you need to do changes during the testing. To achieve the squash we will use the interactive rebase.

git rebase -i HEAD~N

The N is the number of commits you want to squash. E.g. you want to squash your last 5 commits change the variable N to 5. After you hit enter a list of N commits occurs and you have different kind of options to manipulate these.

pick 8b6031b268 BUG-1: First fix
squash 705e6539a6 BUG-2: Second fix
squash cb7e48aa1c BUG-3: Third fix
squash 83e8d3b951 BUG-4: Fourth fix
squash 6429bcce62 BUG-5: Final fix

Change the keyword pick to squash for the commits which should be merged into the first fix. Leave the keyword pick for the first commit. Save the file. Afterwards, you will be asked, which commit message you want to use for the commit. You can comment out the one you don’t want to use. Save the file and you did it. Now you can check your log-tree by using the command:

git log

Squash commits after push

You can squash also commits which are already pushed to origin. The process is the same. Squash the number of commits:

git rebase -i origin/[branch]~N [branch]

Now it’s necessary to force our changes to the remote repository with the following command:

git push origin +[branch]

Corner case for initial commit

There exist a corner case if you want to squash the second commit to the initial commit. In this case, you can’t use the HEAD or the commit hash. Instead, you have to use the --root argument.

git rebase -i --root

This is a nice feature in Git. I have used it a couple of times. I hope this article helps you to squash your commits, too. Let a comment and check out my newest articles.

chevron_left
chevron_right

Leave a comment

Your email address will not be published. Required fields are marked *

Comment
Name
Email
Website

This site uses Akismet to reduce spam. Learn how your comment data is processed.