Combining Multiple Git Commits

Using Git, it is possible to combine multiple commits into a single commit with interactive rebasing.

The first step is to select the commits that you want to combine. Here is an example of selecting the last 3 commits:

1
git rebase -i HEAD~3

This will open your text editor and display:

1
2
3
4
5
6
7
8
9
10
pick e520ab4 example commit message
pick 937b3bb another example commit message
pick 2ab71fc and another example commit message

# Rebase e520ab4 ..2ab71fc onto 19ac48b
#
# Commands:c
#  p, pick = use commit
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit

Changing all of the items below the top one to “squash” will combine the commits:

1
2
3
4
5
6
7
8
9
10
pick e520ab4 example commit message
squash 937b3bb another example commit message
squash 2ab71fc and another example commit message

# Rebase e520ab4 ..2ab71fc onto 19ac48b
#
# Commands:
#  p, pick = use commit
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit

After you save and close that text editor, another text editor will open. This will allow you to re-write the commit message:

1
2
3
4
5
6
7
8
9
# This is a combination of 3 commits.
# The first commit's message is:
example commit message

# This is the 2nd commit message:
another example commit message

# This is the 3rd commit message:
and another example commit message

Write your new commit message, save, and close. Your three commits are now combined into one single commit.