How to squash multiple commits into one in Git

· Category: Git

Short answer

Use git rebase -i HEAD~N (where N is the number of commits to combine), mark all but the first commit as squash, save, and edit the combined commit message. For more on rebasing, see what is the difference between Git merge and Git rebase.

Steps

  1. Run git rebase -i HEAD~3 to combine the last 3 commits
  2. In the editor, leave the first as pick, change others to squash
  3. Save and close the editor
  4. Edit the combined commit message in the next editor
  5. Save and close

Example rebase todo

pick a1b2c3d Add login form
squash d4e5f6g Fix validation
squash h7i8j9k Add tests

Tips

  • Never rebase commits that have been pushed to a shared branch
  • Use git rebase --abort to cancel if something goes wrong
  • For undoing commits without squashing, see how to revert a commit in Git