Why Squash Commits?
If you’ve been working with Git for a while you might start to wonder why you can’t combine that last trivial “hello world” type commit with your previously more meaningful commit.
Fortunately, you don’t have to wonder as Git provides a nice way to do this.
Steps for Squashing Your Last 2 Git Commits
Let’s say your git log looks like this:
1 af81b37 - (HEAD feature_w) Fixed typo in feature name (2 minutes ago) 2 da9ee9b - Added new feature W (11 minutes ago) 3 g392876 - Added new feature Z (2 days ago)
To squash the last 2 commits, at the command prompt type:
1 git rebase -i HEAD~2
This will open up your text editor with the following lines:
1 pick da9ee9b Added new feature W (11 minutes ago) 2 pick af81b37 Fixed typo in feature name (2 minutes ago)
Now you can tell Git what you want to do with each commit – pick, edit, or squash a commit.
Let’s change it to the following since fixing a typo is not really a worthwhile commit message.
1 pick da9ee9b Added new feature W (11 minutes ago) 2 squash af81b37 Fixed typo in feature name (2 minutes ago)
When you’re finished just save and Git will squash your commits.
Caution: Don’t squash commits that have already been shared with others via a public push/pull. It will mess up the history and cause you headaches.