Guide
How to squash git commits without an editor
Squashing turns several commits into one. Which command fits depends on whether the commits are the most recent ones and whether you want to keep their messages.
Squash the last N commits: soft reset
To combine your last three commits into one, move the branch back three commits while keeping all their changes staged, then commit once:
git reset --soft HEAD~3 git commit -m "Add settings page"
No editor opens, and nothing in your working tree changes. To reuse the oldest commit’s message instead of writing a new one, run git commit -C ORIG_HEAD~2 in place of the second line (ORIG_HEAD is the tip before the reset).
Fold a fix into an earlier commit: --fixup and --autosquash
If you spot a mistake in a commit further back, commit the fix marked as a fixup of that commit, then let git move and squash it for you:
git commit --fixup 4c5d6e7 GIT_SEQUENCE_EDITOR=: git rebase -i --autosquash 4c5d6e7~1
GIT_SEQUENCE_EDITOR=: accepts git’s plan without opening an editor. The fix is folded into 4c5d6e7 and its message is dropped. Use git commit --squash instead of --fixup to keep both messages. Set git config --global rebase.autoSquash true to make --autosquash the default.
Pick and choose: interactive rebase
When the commits aren’t adjacent, or you want to squash some and keep others, edit the plan by hand:
git rebase -i HEAD~4 pick 1a2b3c4 Add settings page squash 5d6e7f8 Fix typo in settings page fixup 9a8b7c6 Fix lint pick 2b3c4d5 Add billing page
Change pick to squash to combine a commit with the one above it and keep both messages, or to fixup to combine it and drop its message. Save and close. If you used squash, git opens an editor once more for the combined message.
Before you squash
- Squashing rewrites commits. If you already pushed them, you’ll need
git push --force-with-lease, so don’t do it on a branch others are building on. - Don’t squash across merge commits. A plain rebase flattens them.
- If it goes wrong,
git reset --hard ORIG_HEADright after the rebase takes you back. See how to undo a git rebase.