Interactive Rebase in Git
Combining Commits (Squashing)
Combining Commits (Squashing)
The squash is an interactive rebase operation that allows you to combine multiple commits into a single one. This is useful for cleaning up the commit history to make it more readable and coherent, especially before merging a branch into the main one.
When to Use Squash?
- To group small changes: If you've made multiple commits with minor changes, you can combine them into a single commit.
- When you've made mistakes: You can combine a commit that fixes errors with the original commit where the error was introduced.
- To improve readability: A cleaner commit history is easier to read and understand for other developers.
How to Squash Commits
Suppose you have the following commit history:
plaintext
And you want to combine the last two commits (Add new feature
and Fix typo
) into a single one. To do this, start an interactive rebase over the last four commits:
bash
In the interactive rebase file, change the pick
command of Fix typo
to squash
(or s
):
plaintext
Merging Commit Messages
After saving and exiting the editor, Git will ask you to combine the commit messages. Open a new editor where you can edit the merged commit message. The content will look something like this:
plaintext
You can edit this message to create a more coherent commit message. For example:
plaintext
Save and close the editor to complete the squash
.
Verification
To confirm that the commits have been combined correctly, you can check the commit history:
bash
You should see that the two commits have now been merged into one:
plaintext