Squashing commits in Git is a way to combine multiple commit entries into one, which can help in maintaining a clean and readable project history. Here’s how you can squash commits on a branch:

Steps to Squash Commits:

Open your terminal: Make sure you’re in the root directory of your Git project.

Check out the branch: Switch to the branch where you want to squash commits.

git checkout your-branch-name

Identify the commits to squash: Decide how many commits you want to squash. For example, if you want to squash the last 3 commits, you’ll use HEAD~3.

Start an interactive rebase: Use the interactive rebase command to begin the squashing process.

git rebase -i HEAD~3

This will open an interactive rebase interface in your default text editor.

Mark commits for squashing:

  • In the interactive rebase interface, you will see a list of commits.
  • The first commit in the list should be marked as pick.
  • For the subsequent commits that you want to squash, replace pick with squash or s.

For example:

pick abc1234 First commit message
squash def5678 Second commit message
squash ghi9012 Third commit message

Save and close the editor: After marking the commits, save the changes and close the text editor. This will start the rebase process.

Edit the commit message: After squashing, Git will prompt you to edit the commit message for the combined commit. You can write a new commit message that appropriately describes the changes of the squashed commits.

Complete the rebase: Save the commit message and close the editor. Git will complete the rebase and squash the commits into one.

Example:

Here’s an example where we squash the last 3 commits:

Check out the branch:

git checkout feature-branch

Start interactive rebase:

git rebase -i HEAD~3

Interactive rebase interface:

pick abc1234 Add feature A
squash def5678 Improve feature A
squash ghi9012 Fix bug in feature A

Edit commit message:

Add feature A, improve it, and fix a bug

Pushing Changes:

After squashing commits, if the branch is already pushed to a remote repository, you will need to force-push the changes:

git push origin your-branch-name --force

Note: Force-pushing can overwrite history, so use it with caution, especially if others are working on the same branch.

By following these steps, you can effectively squash commits and maintain a cleaner Git history.

Simon

102 Articles

I love talking about tech.