How to squash the last X commits together in git?

Initially, when I started working on git, I was terrified of squashing commits, I always feared that I would do it wrong and will lose some code, but it's very simple once you understand the underlying logic.

In this example, we'll squash the last three 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, 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 methods squash the last three commits into a single new commit similarly. The soft reset re-points HEAD to the last commit you do not want to squash. Neither the index nor the working tree is 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 you are about to "throw away").

Originally Posted On: StackOverflow

Subscribe to GIT.WTF!?!

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe