Combining multiple commits before pushing in Git [duplicate] Combining multiple commits before pushing in Git [duplicate] git git

Combining multiple commits before pushing in Git [duplicate]


What you want to do is referred to as "squashing" in git. There are lots of options when you're doing this (too many?) but if you just want to merge all of your unpushed commits into a single commit, do this:

git rebase -i origin/master

This will bring up your text editor (-i is for "interactive") with a file that looks like this:

pick 16b5fcc Code in, tests not passingpick c964dea Getting closerpick 06cf8ee Something changedpick 396b4a3 Tests passpick 9be7fdb Better commentspick 7dba9cb All done

Change all the pick to squash (or s) except the first one:

pick 16b5fcc Code in, tests not passingsquash c964dea Getting closersquash 06cf8ee Something changedsquash 396b4a3 Tests passsquash 9be7fdb Better commentssquash 7dba9cb All done

Save your file and exit your editor. Then another text editor will open to let you combine the commit messages from all of the commits into one big commit message.

Voila! Googling "git squashing" will give you explanations of all the other options available.


If you have lots of commits and you only want to squash the last X commits, find the commit ID of the commit from which you want to start squashing and do

git rebase -i <that_commit_id>

Then proceed as described in leopd's answer, changing all the picks to squashes except the first one.

Example:

871adf OK, feature Z is fully implemented      --- newer commit --┐0c3317 Whoops, not yet...                                         |87871a I'm ready!                                                 |643d0e Code cleanup                                               |-- Join these into oneafb581 Fix this and that                                          |4e9baa Cool implementation                                        |d94e78 Prepare the workbench for feature Z     -------------------┘6394dc Feature Y                               --- older commit

You can either do this (write the number of commits):

git rebase --interactive HEAD~[7]

Or this (write the hash of the last commit you don't want to squash):

git rebase --interactive 6394dc


There are quite a few working answers here, but I found this the easiest. This command will open up an editor, where you can just replace pick with squash in order to remove/merge them into one

git rebase -i HEAD~4

where, 4 is the number of commits you want to squash into one. This is explained here as well.