How Do You Squash Commits in Git?

Squashing commits in Git is a technique used to combine multiple commits into a single, more cohesive commit. This can be useful for cleaning up your commit history before merging a feature branch into the main branch, ensuring that the history is concise and meaningful. In this article, we’ll cover how to squash commits using Git’s interactive rebase feature.

When to Squash Commits

Squashing commits is often done before merging a branch into the main branch to create a cleaner, more organized commit history. It’s particularly useful when you have many small commits that represent incremental changes or corrections that can be logically grouped together.

How to Squash Commits Using Interactive Rebase

Step 1: Start an Interactive Rebase

To begin squashing commits, start an interactive rebase by running:

git rebase -i HEAD~n

Replace n with the number of commits you want to squash. For example, if you want to squash the last three commits, you would use:

git rebase -i HEAD~3

Step 2: Mark Commits for Squashing

An interactive rebase screen will open in your default text editor, listing the commits to be rebased. The commits will be listed with the word pick next to each one. To squash commits, leave the first commit as pick and change the others to squash or s:

pick commit1
squash commit2
squash commit3

This configuration tells Git to keep the first commit as is and squash the following commits into it.

Step 3: Edit the Commit Message

After squashing, Git will prompt you to edit the commit message. You can combine the messages of the squashed commits into a single, meaningful message or write a new one that summarizes the changes:

# This is a combination of commits.
# Please enter the commit message for your changes.

Save and close the editor to complete the rebase process.

Step 4: Push the Changes

If you have already pushed the original commits to a remote repository, you’ll need to force push the squashed commit:

git push --force-with-lease

Using --force-with-lease is safer than --force, as it checks that the remote branch hasn’t been updated by others before pushing.

Best Practices for Squashing Commits

  • Use Squashing for Cleanup: Squash commits to tidy up your history before merging to the main branch, but avoid over-squashing, as some commit granularity is valuable for understanding changes.
  • Communicate with Your Team: If working in a team, coordinate with others before force-pushing squashed commits to avoid disrupting their work.
  • Squash Locally: Prefer to squash commits before pushing them to a shared repository. This avoids the need to force-push, which can affect collaborators.

Conclusion

Squashing commits in Git is a useful technique for maintaining a clean and readable commit history. By using interactive rebase, you can combine multiple related commits into a single, meaningful commit that clearly communicates the purpose of your changes.