Home Git Squash 🎃 A Powerful Tool for Cleaning Up Your Commit History
Post
Cancel

Git Squash 🎃 A Powerful Tool for Cleaning Up Your Commit History

The Problem it Solves

Git squash is a way to combine multiple commits into a single commit. This can be useful for cleaning up a branch with many small, insignificant commits before merging it into the main branch. Squashing commits also makes it easier to read the commit history and understand the changes that were made.















Let’s 🎃 a messy commit

To squash commits, first, make sure you are on the branch that contains the commits you want to squash. To then squash commits, you will first need to use the git log command to view the history of your branch. This will show you a list of all the commits on your branch, along with their SHA-1 hashes. You will need these hashes to reference the commits you want to squash.

1
git log

This git log command will show you a list of the commits on the branch, along with their commit messages and hashes. The most recent commit will be at the top of the list.

Next, use the git rebase command to move the branch pointer to the commit you want to start the squash at.
For example, if you want to squash the last three commits on your branch, you would run the following command:

1
git rebase -i HEAD~3

For our example since we are trying to squash the last three commits, this git rebase -i HEAD~3 command will open a text editor with a list of the last three commits on your branch. The text editor will be in “interactive” mode, which means you can use special keywords to tell Git what to do with each commit.

To squash the last three commits into a single commit, you would change the keyword for each commit from pick to squash. Your file should now look something like this:

1
2
3
pick abc123 Commit 1
squash def456 Commit 2
squash ghi789 Commit 3

Save and close the file. Git will then combine the changes from the last three commits into a single commit, and open another text editor for you to enter a commit message for the new, squashed commit.

Once you have entered a commit message and saved the file, Git will apply the squashed commit to your branch. You can use the git log command to verify that the squashed commit has been added to your branch history.

Conclusion

That’s it! You’ve successfully squashed multiple commits into a single commit. You can verify this by running git log again, which should now show only a single commit with the new commit message you entered.

In summary, git squash is a way to combine multiple commits into a single commit. This can make it easier to read the commit history and understand the changes that were made. Squashing commits can also be useful for cleaning up a branch before merging it into the main branch.

This post is licensed under CC BY 4.0 by the author.