Last Updated: February 25, 2016
· splinterofchaos

Clean your branch's history before commiting.

You make a small change to the code, but it's incomplete; doesn't compile or fully implement the feature you want. You want to save your work and try something, but you don't want your history littered with small or incorrect commits. Commit anyway! You can squash a bunch of commits together to make your log more brief.

When you're done with the feature, run

$ git rebase -i <master/develop/other>

The -i stands for interactive and prompts the fallowing screen:

pick 9977ead Commit 2+1/2
pick e1f203f Commit 2+2/2
pick 1a07d53 Commit 3

## Below this is what git added to the file. 
# Rebase 17a84ad..1a07d53 onto 17a84ad
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.

I have made a small repository with 4 commits, however the first isn't shown since i'm rebasing onto it. I want to squash commits 2+1/2 and 2+2/2 together, then rewrite the third commit, so i change to this:

pick 9977ead Commit 2+1/2
squash e1f203f Commit 2+2/2
reword 1a07d53 Commit 3

squash tells git to combine the commit with the one above it. If i wanted to squash every commit together, i could just change reword to squash as well. Git can squash as many consecutive commits together as you want. reword just lets you edit the commit message.

After saving and exiting the editor, git will automatically squash the commits and let you edit the message.

# This is a combination of 2 commits.
# The first commit's message is:

Commit 2+1/2

# This is the 2nd commit message:

Commit 2+2/2

Since i specified reword for the last commit, git immediately jumps to what basically equates to a git commit --amend (since this commit is on top). Now, i can merge with master, or any branch of my choice, and do so with a clean and elegant history.

With the knowledge that git allows one to edit their history, one should never feel afraid to save their code. One should never be thinking about how they want to manage their tree when they should be coding. Even writing a detailed commit message may be delayed in order to keep one's rythm or flow.

Alternatively, one could use git commit --amend frequently to add small, incremental changes, however this doesn't offer the same power of rebasing.