0
0
Gitdevops~5 mins

Squashing commits in Git - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes your git history has many small commits that clutter the log. Squashing commits means combining several commits into one to keep history clean and easier to understand.
When you have multiple small fixes that should be one logical change before sharing your work.
Before merging a feature branch into the main branch to keep history tidy.
When you want to rewrite commit messages for clarity and consistency.
If you accidentally committed work in several steps but want to present it as a single update.
When cleaning up your branch history before pushing to a shared repository.
Commands
Shows a short list of recent commits with their IDs and messages to identify which commits to squash.
Terminal
git log --oneline
Expected OutputExpected
a1b2c3d Fix typo in README f4e5d6c Add user login feature 7g8h9i0 Initial commit
--oneline - Shows each commit in one line with short ID and message
Starts an interactive rebase for the last two commits so you can choose to squash them into one.
Terminal
git rebase -i HEAD~2
Expected OutputExpected
pick f4e5d6c Add user login feature pick a1b2c3d Fix typo in README # Rebase 7g8h9i0..a1b2c3d onto 7g8h9i0 (2 commands) # # Commands: # p, pick = use commit # s, squash = use commit, but meld into previous commit # ...
-i - Interactive mode to edit commits
Check the commit history after squashing to confirm the commits were combined.
Terminal
git log --oneline
Expected OutputExpected
a1b2c3d Add user login feature and fix typo in README 7g8h9i0 Initial commit
--oneline - Shows concise commit history
Key Concept

If you remember nothing else from this pattern, remember: interactive rebase lets you combine multiple commits into one clean commit.

Common Mistakes
Using git rebase -i without specifying the correct number of commits
You might miss the commits you want to squash or include too many unrelated commits.
Count how many commits back you want to edit and use HEAD~N where N is that number.
Not changing 'pick' to 'squash' or 'fixup' in the interactive rebase editor
The commits will not be combined and the rebase will just replay them as separate commits.
Change 'pick' to 'squash' for the commits you want to merge into the previous one.
Squashing commits that have already been pushed to a shared repository
It rewrites history and can cause conflicts for others working on the same branch.
Only squash commits before pushing or coordinate with your team if rewriting shared history.
Summary
Use 'git log --oneline' to see recent commits and decide which to squash.
Run 'git rebase -i HEAD~N' to start interactive rebase for the last N commits.
In the editor, change 'pick' to 'squash' to combine commits, then save and exit.
Verify the new commit history with 'git log --oneline' to confirm the squash.