Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Squash my last X commits together using Git

How can I squash my last X commits together into one commit using Git?

like image 796
markdorison Avatar asked Mar 04 '11 04:03

markdorison


People also ask

How would you squash multiple commits together using git merge -- squash?

In case you are using the Tower Git client, using Interactive Rebase to squash some commits is very simple: just select the commits you want to combine, right-click any of them, and select the "Squash Revisions..." option from the contextual menu.

How do you squash last n commits into a single commit in git?

You can use git merge --squash for this, which is slightly more elegant than git rebase -i . Suppose you're on master and you want to squash the last 12 commits into one. The documentation for git merge describes the --squash option in more detail.

How do I merge last commits?

If you want to merge the last 2 commits into one and look like a hero, branch off the commit just before you made the last two commits (specified with the relative commit name HEAD~2). That will bring in the changes but not commit them. So just commit them and you're done.


1 Answers

You can do this fairly easily without git rebase or git merge --squash. In this example, we'll squash the last 3 commits.

If you want to write the new commit message from scratch, this suffices:

git reset --soft HEAD~3 && git commit 

If you want to start editing the new commit message with a concatenation of the existing commit messages (i.e. similar to what a pick/squash/squash/…/squash git rebase -i instruction list would start you with), then you need to extract those messages and pass them to git commit:

git reset --soft HEAD~3 &&  git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})" 

Both of those methods squash the last three commits into a single new commit in the same way. The soft reset just re-points HEAD to the last commit that you do not want to squash. Neither the index nor the working tree are touched by the soft reset, leaving the index in the desired state for your new commit (i.e. it already has all the changes from the commits that you are about to “throw away”).

like image 101
Chris Johnsen Avatar answered Oct 24 '22 13:10

Chris Johnsen