Git & GitHub - Squashing Commits
How to squash commits in Git
Squashing commits in Git involves combining multiple commits into a single commit. This can simplify the commit history and make it easier to manage. This guide covers how to squash commits effectively using interactive rebase and other techniques.
Key Points:
- Squashing commits helps to keep the commit history clean and readable.
- Interactive rebase is a common method for squashing commits.
- Squashing should be done before pushing to a shared repository to avoid conflicts.
Squashing Commits Using Interactive Rebase
Step 1: Start an Interactive Rebase
Use the git rebase -i
command followed by the commit hash or HEAD~n
to specify the range of commits you want to squash:
# Example: Start an interactive rebase for the last 3 commits
$ git rebase -i HEAD~3
Step 2: Edit the Rebase Todo List
In the interactive rebase editor, replace pick
with squash
(or s
) for the commits you want to squash into the previous commit. The first commit should remain as pick
:
pick abc123 First commit
squash def456 Second commit
squash ghi789 Third commit
Step 3: Save and Exit the Editor
After editing the rebase todo list, save and exit the editor. Git will proceed with squashing the commits.
Step 4: Edit the Commit Message
Git will open a new editor window to combine the commit messages. Edit the combined commit message as needed, save, and exit the editor:
# Example combined commit message
First commit
Additional details from second commit
Additional details from third commit
Step 5: Complete the Rebase
Git will complete the rebase and apply the squashed commit to your branch. Verify the changes using git log
:
# Verify the commit history
$ git log
Squashing Commits During a Merge
You can also squash commits during a merge by using the --squash
option:
# Example: Squash and merge a feature branch into main
$ git checkout main
$ git merge --squash feature-branch
# Commit the squashed changes
$ git commit -m "Merged feature-branch with squashed commits"
Best Practices
Follow these best practices when squashing commits:
- Squash Before Pushing: Squash commits before pushing to a shared repository to avoid conflicts.
- Write Clear Commit Messages: Write clear and concise commit messages that describe the combined changes.
- Use Interactive Rebase for Editing History: Use interactive rebase to squash, edit, or reorder commits as needed.
Summary
This guide covered how to squash commits in Git, including using interactive rebase, squashing during a merge, and best practices. Squashing commits helps to maintain a clean and readable commit history, making it easier to manage and review changes.