乐闻世界logo
搜索文章和话题

Git: How to Squash the Last N Commits into One?

2024年7月4日 00:26

When using Git for version control, you may sometimes need to squash multiple commits into one to maintain a clean project history and streamline management. Git offers a commonly used tool, git rebase, especially when used with the interactive mode. I will now provide a detailed explanation of how to squash the last N commits into one.

Steps

  1. Locate the branch to modify

First, ensure you are on the branch you want to modify. If not, switch to it using:

bash
git checkout branch-name
  1. Start interactive rebase

Start an interactive rebase using git rebase to rebase the last N commits:

bash
git rebase -i HEAD~N

Here, N represents the number of commits to rebase back, and HEAD~N indicates the position N commits before the current HEAD.

  1. Select commits to squash

In the editor that opens, you'll see a list of the last N commits, each prefixed with pick. For all commits except the top one, change the pick line to squash or its shorthand s to indicate that you want to squash these commits into the previous pick-marked commit.

For example, if you have three commits and want to squash them into one, you'll see a list like:

shell
pick a1b2c3 First commit pick d4e5f6 Second commit pick g7h8i9 Third commit

Change it to:

shell
pick a1b2c3 First commit squash d4e5f6 Second commit squash g7h8i9 Third commit
  1. Edit commit message

After confirming the squash, Git will prompt you to edit the new commit message. Here, you can choose to retain one or more of the original commit messages or write a completely new description.

  1. Complete the rebase operation

After editing and saving the commit message, Git will reapply the changes and squash the commits. Finally, use git log to verify the squashed commit history as expected.

Example

Suppose I'm working on a project with a series of small bug fixes and code improvements, all as consecutive commits. Before merging the branch into the main branch, I need to consolidate these small commits into a single larger commit to facilitate subsequent code reviews and merges.

Using this method, I can easily consolidate these small commits, not only making the project history clearer but also helping colleagues understand the overall intent of the changes.

Notes

  • Before squashing with git rebase, ensure no other team members are working on these commits, as rebasing changes the commit history.
  • If you're working on a public branch, ensure all team members are aware of your changes to avoid potential merge conflicts.
标签:Git