All How-Tos
Intermediate

How to Squash Several Commits into One in Git

Learn how to combine several local commits into one before sharing your work.

Prepare the Squash

The example combines the latest three commits on your local feature branch. It assumes a linear history with an earlier commit before those three.

Your working tree and Index should be clean. Commit or stash unfinished edits first, then review the commits and save a backup under an unused branch name.

git log --oneline -3
git branch --no-track backup/before-squash

Combine the Commits

  • Start an Interactive Rebase: HEAD~3 selects the parent of the three commits. --no-autosquash keeps the action list in commit order even if automatic fixup handling is configured. --no-update-refs keeps the backup and other branch references in place during the rewrite.
git rebase --interactive --no-autosquash --no-update-refs HEAD~3
  • Edit the Action List: Git lists the selected commits oldest first. Keep the first action as pick and change the next two to squash. Keep the actual commit IDs shown in your editor; the IDs below are illustrative. Save and close the editor.
pick a1b2c3d4e5f6 Add login form
squash b2c3d4e5f6a1 Validate login fields
squash c3d4e5f6a1b2 Add login form tests
  • Write the Combined Message: When Git opens the commit message editor, replace the collected messages with a description of the completed change. Save and close the editor to finish.

Check the Result

An empty diff confirms that the final tracked files match your backup. The log should now show one commit in the range that previously contained three.

git diff backup/before-squash HEAD
git log --oneline backup/before-squash~3..HEAD

Considerations

  • Replace 3 with the number of latest commits you want to combine, including in the verification range. This recipe assumes the selected range contains no merge commits.
  • Use fixup instead of squash for the later commits if you want to keep the first commit's message and discard the later messages while still including their changes.
  • Squashing replaces commit IDs. Use it for unshared commits; rewriting published history requires coordination with collaborators.
  • To cancel an unfinished rebase, run git rebase --abort. If it stops with conflicts, resolve the files, stage them with git add, and run git rebase --continue to proceed.
  • After completion, backup/before-squash still points to the original history for comparison or recovery.
  • To correct only the last commit, see Amend the Last Commit.