How to Combine multiple Commits in Git

The ability to combine multiple commits in Git is a huge plus. Combining commits requires “rebasing” which will essentially rewrite the project history appending commits onto the last commit (by default) in a different branch, or even to an earlier commit in the same branch.

Rebasing can have some damaging effects, so be careful when using it. A good best practice is to never use rebase on a public branch. Below is an example of cleaning up commits in a single branch.

First, we use a few simple bash commands which will initialize a Git repo and make several commits. The first few commits simply add lines to the file. The last commit fixes a spelling error from a previous commit.

We can see the commit history by using the git log command:

If we decide that we would like to combine several of these commits to clean things up, we can with git rebase -i.

Using git rebase -i HEAD~5 will allow us to rebase the head of the current branch against this same branch 5 commits ago.

After executing this command, the default editor will open a file like this, that includes a list of commits and instructions on how to use rebase.

Changing pick to squash or fixup will combine a commit into the previous commit. When using squash, you are prompted to update the commit message in the default editor. These 5 original commits will be combined into 2.

Now using the git log command we can see our new git history with 3 total commits instead of 6.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">