How To Combine Git Commits — Rebase And Squash

Sachithra Dangalla
2 min readNov 28, 2020

--

This post explains how to combine git commits by using git rebase and git squash.

Let’s assume that we have a couple of commits as follows that we wish to combine into one commit. You can use git log --online to view a summary or shortened version of git log output.

Let’s assume that we have a couple of commits as follows. — oneline gives the short version of git log output. It will open up vim editor and you can type :q to exit it without saving. (Some useful vim commands can be found at the end of the post)

$ git log --oneline  
c123456 Edit file-B again
b234567 Edit file-B
a012345 Edit file-A

As you can see, there are 2 commits that edits a certain file-B and we want to combine those commits into one.

So first of all, we have to go back a step and rebase into the commit that happened before our intended 2 commits, i.e. the “Edit file-A”. So copy the commit ID and use the following command to rebase:

git rebase -i a012345

The above command will open the editor with commit info up to the specified commit. Type i to enter into the Insert mode and edit the log as follows:

pick b234567 Edit file-B  
squash c123456 Edit file-B again

In the above commands we tell git to “squash” the unwanted commit.

Press Esc and type :wq to save and exit the editor. And that’s it! You can check the commit logs again to ensure the results.

If you have already pushed your changes to a remote, you might need to force push your changes using --force. E.g. git push origin --force

Hope you learned something today! Cheers!

Quick tips: vim commands

  • :wq — to save and exit
  • :q — exit without saving
  • i — to enter Insert mode
  • Esc — to enter Command mode from Insert mode

Google more on vim commands.

--

--

Sachithra Dangalla
Sachithra Dangalla

No responses yet