How to Combine Multiple Commits into One
- Steps to merging multiple commits
An interactive rebase mode allows you to combine your commits into even one singular commit. If you wonder why you should do this, imagine a branch with a lot of commits that contain minor changes.
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.
1. Running git rebase in interactive mode
Firstly, you should run git rebase in interactive mode and provide the parent commit as the argument, like this:
git rebase -i HEAD~3
2. 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 typing squash at the beginning of the second line and save the file:
3. Choosing between commit messages
One more editor window will show up to change the resulting commit message. There will be combined messages. If you want your second commit message to be the same as the first one, you can simply remove it and save the file, like this:
4. Pushing changes
You should run git push to add a new commit to the remote origin. In case if you were already pushed the multiple commits, you should force update the remote origin by running:
git push origin HEAD -f
When you work on some new feature you make several intermittent commits in the history. It is more convenient to have all of the commits combined into one.
There is no git squash command in Git. Squashing pull request means to combine all the commits in that request into one to make it easier to read and clean the history of the main branch. To achieve that you should to use interactive mode of the git rebase command described above.
The squashing process is dangerous if your branch has already been published in the remote repository. Thus, it is best to squash on the local branch before pushing. If you have already pushed it, then, for creating pull request you should force the changes on the remote branch after squashing operation as the histories of local and remote branches are different.