How to Merge Multiple Commits into One Without Using Merge in Git?
When using Git for version control, you may sometimes need to merge multiple commits into a single commit to keep the project history clean. In Git, this is typically achieved through an interactive rebase, which does not affect other parts of the project.
Steps:
-
Start Interactive Rebase: Open the terminal, first determine the base branch you want to merge commits into, assuming it is the
mainbranch, and you want to merge the last four commits. You can use the following command:bashgit rebase -i HEAD~4 -
Select Commits to Merge: After executing the above command, Git opens a window in the default text editor listing the last four commits, each prefixed with
pick. For example:shellpick e3a1b35 First commit message pick 7ac9a67 Second commit message pick 1d2a3f4 Third commit message pick 76b9e7f Fourth commit messageTo merge these commits into one, keep the first
pickunchanged and change the others tosquashor its shorthands, which merges these commits into the previous one.shellpick e3a1b35 First commit message squash 7ac9a67 Second commit message squash 1d2a3f4 Third commit message squash 76b9e7f Fourth commit message -
Rewrite Commit Message: After saving and closing the editor, Git opens another editor window to allow you to edit the new commit message. Here, all merged commit messages are listed, and you can edit them to create a new commit message or choose one as the entire commit's message.
-
Complete Rebase: After completing the edit and saving, Git applies these changes. If there are no conflicts, your commit history should now be integrated into a single commit.
Example Usage Scenario:
Suppose you make multiple commits during development, involving temporary debugging code additions and deletions, or multiple minor formatting adjustments. In this case, to avoid these 'noise' commits polluting the main branch's history, you can merge them into a single commit before pushing to the main branch, keeping the main branch history clean for future code reviews and maintenance.
Note:
Using rebase to merge commits rewrites history. If these commits have already been pushed to a shared remote branch, using git push --force may affect other collaborators. Therefore, this approach is better suited for unpushed local commits.