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

How to Squash the Last N Commits into a Single Commit in Git?

2024年7月4日 22:01
  1. Open the command line terminal: First, ensure your terminal or command line window is open and you have navigated to your project directory.

  2. Execute an interactive rebase: Run the following command to initiate an interactive rebase. Here, HEAD~N refers to moving back N commits from the current HEAD, operating on the last N commits.

bash
git rebase -i HEAD~N

For example, to squash the last three commits, use:

bash
git rebase -i HEAD~3
  1. Select and modify commits: After executing the command, your default text editor will open a file listing the commits to be squashed. Each commit has a pick keyword. To squash these commits, change the pick keyword for all commits except the first one to squash or s, indicating you want to merge them into the preceding commit.

Example content:

plaintext
pick e3a1b35 First commit to squash squash 7ac9a67 Second commit to squash squash d2ed9f2 Third commit to squash
  1. Merge commit messages: After saving and closing the editor, Git will attempt to automatically merge the commits. If necessary, it will reopen the text editor for you to edit the final commit message. Here, you can organize, edit, or combine the original commit messages.

  2. Complete the rebase: After saving the final commit message and closing the editor, the rebase process completes. Verify the updated commit history using git log to ensure everything meets your expectations.

  3. Update the remote repository (if needed): If you have already pushed these commits to a remote repository, force-push is required to update the remote history due to changes. Execute the following command:

bash
git push origin <branch-name> --force

Note: Force-pushing rewrites the remote repository's history. In team environments, this may impact collaborators. Always confirm it is safe or communicate with team members before proceeding.

This method enables you to effectively manage and organize your commit history, resulting in a clearer and more structured repository.

标签:Git