Git·19 questions

How to squash multiple commits into one?

Answer

Squash — combining multiple commits into one. This is useful when you've made many small commits in a feature branch ("wip", "fix typo", "fix again") and want to present them as one clean commit in history.

Via interactive rebase: git rebase -i HEAD~4, where 4 is the number of commits to combine. An editor opens with a list of commits. Each commit is marked with the word pick. Change pick to squash (or just s) for commits you want to combine with the previous one. Leave the first commit as pick — it will be the base. Save and close the editor. A second editor opens for editing the combined commit message — write a clean description of all changes.

Example: you have 4 commits — "feat: add form", "fix: validation", "typo", "style: button". Run git rebase -i HEAD~

Change: pick a1b2c3d feat: add form squash d4e5f6g fix: validation squash h7i8j9k typo squash l0m1n2o style: button

After saving, write a new message: "feat: add registration form with validation and styling". You get one commit instead of four.

Via git merge --squash: when merging a feature branch into main, run git merge --squash feature-branch. Git combines all changes but doesn't create a merge commit. Then git commit -m "feat: add registration form" — one commit with all changes. This is simpler but loses the feature branch history.

Via git reset --soft: to combine the last N commits, run git reset --soft HEAD~N. All changes from N commits gather in the index. Then git commit -m "new message" — one commit instead of N. Fast, but doesn't let you choose which commits to combine.

After squash on an already pushed branch: git push --force-with-lease. History is rewritten, so a force-push is needed. Warn the team if the branch is shared.

Good practice: do squash before merging a feature branch into main. This gives a clean main history where each commit is one completed feature, not a series of "wip" and "fix typo".

Was this answer helpful?

More questions in this topic

Related questions from other topics