Squash recent commits into one

Medium risk
What do risk levels mean?
Read-only
Inspects state without changing anything.
Low risk
Reversible with a routine follow-up command.
Medium risk
Changes state; undo path documented.
Destructive
Deletes or overwrites; confirmation required.

Combines the last several commits on the current branch into a single commit, keeping all their changes but replacing the commit history.

gitsquashhistory

Parameters

How many commits from the tip to squash together.

Commands

Review the commits that will be squashed

git log --oneline -2

Remove the commits while keeping all their changes staged

git reset --soft HEAD~2

Create one new commit containing the combined changes

git commit

Verification

git log --oneline -3

The squashed commits are replaced by a single new commit.

Undo

Restore the branch tip to before the reset, using the reflog

git reset --hard 'HEAD@{2}'

Pitfalls

  • Squashing rewrites history; do not squash commits that are already pushed to a shared branch.
  • Count must not exceed the number of commits on the branch, or the reset fails.

Related