How to Combine Multiple Git Commits into One

Prasad Pawar
3 min readMay 14, 2021

Guide for merging multiple git commits

In Git you can merge several commits into one with the powerful interactive rebase. It’s a handy tool I use quite often; I usually tidy up my working space by grouping together several small intermediate commits into a single lump to push upstream.

Steps to merging multiple commits

  1. Running git rebase in interactive mode
  2. Typing “squash”
  3. Choosing between commit messages
  4. Pushing changes
  5. Squashing

An interactive rebase mode allows you to combine your commits into even a single commit. While working in Git, developers often make temporary commits that may have not appropriate commit messages. Before merging those commits to the master, it is necessary to combine them into a single commit with clear and comprehensive commit message. It is essential to do for having a clear commit history.

Steps to merging multiple commits

Let’s see how you can change your dirty history and make it clean by taking some easy steps. The history will have a messy look like this:

This kind of history full of meaningless commits makes it difficult for your team to see your finished product. A quick solution is combining multiple commits into one. To do so, you should follow the steps below.

Running git rebase in interactive mode

Suppose that you want to merge the last 3 commits into a single commit. To do that, you should run git rebase in interactive mode (-i) providing the last commit to set the ones that come after it. Here, HEAD is the alias of the very last commit.

git rebase -i HEAD~3

Note that HEAD~3 means three commits prior to the HEAD. You can select the appropriate commit by its hash.

If you have merge in you commits, it requires different actions.

Typing “squash”

After the first step, the editor window will show up offering you to input the command for each commit. All you need to do is replacing pick with squash, starting from the second line. Then, save the file.

Choosing between commit messages

One more editor window will show up to change the resulting commit message. Here, you can find all your commit messages and change them according to your exact needs.

Pushing changes

You should run git push to add a new commit to the remote origin. If you have already pushed your commits, then you should force push them using the git push command with — force flag (suppose, the name of remote is origin, which is by default)

git push --force origin HEAD

— force overwrites the remote branch on the basis of your local branch. It destroys all the pushed changes made by other developers. It refers to the changes that you don’t have in your local branch.

Yaayy! You are done…

Please let me know in the comments if you face any issues or need any help. See you in the next article.