How can I combine two commits into one commit?

Don P picture Don P · Sep 21, 2012 · Viewed 110.8k times · Source

I have a branch 'firstproject' with 2 commits. I want to get rid of these commits and make them appear as a single commit.

The command git merge --squash sounds promising, but when I run git merge --squash my terminal just brings up options for the command. What is the correct command?

Commit 1:
Added 'homepage.html'
Added 'contacts.html'

Commit 2:
Added 'homepage.php'
Added 'homepage.php'
Deleted 'homepage.html'
Deleted 'contacts.html'

Answer

meagar picture meagar · Sep 21, 2012

You want to git rebase -i to perform an interactive rebase.

If you're currently on your "commit 1", and the commit you want to merge, "commit 2", is the previous commit, you can run git rebase -i HEAD~2, which will spawn an editor listing all the commits the rebase will traverse. You should see two lines starting with "pick". To proceed with squashing, change the first word of the second line from "pick" to "squash". Then save your file, and quit. Git will squash your first commit into your second last commit.

Note that this process rewrites the history of your branch. If you are pushing your code somewhere, you'll have to git push -f and anybody sharing your code will have to jump through some hoops to pull your changes.

Note that if the two commits in question aren't the last two commits on the branch, the process will be slightly different.