How to squash the last N commits together in Git

Git is a distributed version control system designed to handle everything from small to very large projects with speed and efficiency. Git allows multiple developers to work on the same project simultaneously, each with their own local copies of the project. These copies can later be synchronized with the main repository and with each other.

In Git, squashing refers to the process of taking multiple commits and merging them into a single commit. This is often done to clean up a series of smaller changes that should be represented as a single logical change in the repository's history.

Starting the squash process

To squash your last N commits, you'll use the git rebase command in interactive mode (-i). If you want to squash the last 3 commits, you'd do:

git rebase -i HEAD~3
Command to rebase the last commits

This command tells Git to rebase the last 3 commits, and the -i flag initiates the process in interactive mode.

Interactive rebase window

Upon executing the command, an editor (commonly Vim or Nano, depending on your configuration) will open, displaying a list of the last N commits:

pick a1b2c3d First commit message
pick e4f5g6h Second commit message
pick i7j8k9l Third commit message
  • pick: This is a command in the interactive rebase. It means "use this commit" or, in other words, keep the commit as it is.

  • a1b2c3d, e4f5g6h, and i7j8k9l: These are abbreviated commit hashes. They uniquely identify commits in your Git history.

  • First commit message, Second commit message, and Third commit message: These are the commit messages associated with the respective commit hashes.

Crafting the new commit message

After selecting the commits to squash, you'll be prompted to define a new commit message for the squashed commit. This is your chance to provide a concise and descriptive message that encapsulates all the changes.

Completing the squash

Save and close the editor. Git will then squash the specified commits into a single commit with the new message you provided.

Pushing the changes

If you've already pushed commits before squashing, you'll need to force push the changes to overwrite the commit history on the remote repository:

git push origin <your-branch-name> --force
Command to forcefully push to repository

Note: Always exercise caution when force pushing, as it can overwrite changes on the remote repository. Ensure you communicate with your team before performing such actions.

Conclusion

Squashing in Git allows you to combine multiple commits into a single commit, streamlining and tidying up your commit history. It's useful in collaborative environments to maintain a clean and understandable log, ensuring that each commit represents a meaningful, standalone change.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved