Squashing Commits with Git Rebase
In addition to discarding individual commits, Git also provides a way to combine or "squash" multiple commits into a single commit. This is known as "rebasing" and is performed using the git rebase
command.
The git rebase
command allows you to rewrite the commit history by applying a series of commits on top of a new base commit. This can be useful when you have a series of small, incremental commits that you want to combine into a single, more meaningful commit.
Here's an example of how to squash the last three commits into a single commit:
git rebase -i HEAD~3
This will open an interactive rebase editor, where you can specify how you want to modify the last three commits. You'll see something like this:
pick 1234567 Commit 1
pick 2345678 Commit 2
pick 3456789 Commit 3
To squash the commits, you can change the pick
command to squash
(or s
for short) for the commits you want to combine:
pick 1234567 Commit 1
squash 2345678 Commit 2
squash 3456789 Commit 3
After saving and closing the editor, Git will combine the three commits into a single commit, and you'll be able to edit the commit message for the new, squashed commit.
It's important to note that rebasing modifies the commit history, which can be problematic if you have already pushed the commits to a remote repository. In such cases, it's generally better to use the git merge
command instead, which preserves the original commit history.