Git Squash

Squashing Git Commits

To combine several sequential commits in git to a single commit, use git rebase -i to squash the commits.

Note : You can't do this after you've pushed any of the commits.

  1. Run: git rebase -i origin/<branch>
    • Git will bring up your commits in your selected editor. You'll start with something like this:
      pick bccd911 Checkpoint: blah blah
      pick 6d4e448 Added SomeStupidFunction() which does nothing interesting
      pick 690109e Ooops: Added return value to SomeStupidFunction
      
      # Rebase 33612d0..690109e onto 33612d0
      #
      # Commands:
      #  p, pick = use commit
      #  e, edit = use commit, but stop for amending
      #  s, squash = use commit, but meld into previous commit
      #
      # If you remove a line here THAT COMMIT WILL BE LOST.
      # However, if you remove everything, the rebase will be aborted.
      #
      
    • In this case, I want to combine "squash" all of the above into a single commit, so I edit it to be something like this (just the non-comment lines):
      pick bccd911 Checkpoint: blah blah
      s 6d4e448 Added SomeStupidFunction() which does nothing interesting
      s 690109e Ooops: Added return value to SomeStupidFunction
      
    • Save your edits and exit the editor
      • Note : Edits to the commit messages here will have no affect.
      • Note : If you delete a commit line, it'll literally be deleted from git -- you most likely don't want to do this!
    • This will tell git to "squash" the second and third commits into the first. Git will then bring up your editor again to allow you to write up the new combined commit message. In my case, I edited it to this:
      Implemented SomeStupidFunction() which does nothing interesting.
      
  2. Re-run the above git log to verify that you have what you expected:
    • git log origin/<branch>..<branch>