To squash multiple commits into one in Git, you can use the interactive rebase feature. Here's a step-by-step guide:
Open Terminal or Command Prompt: Open a terminal or command prompt window in your Git repository.
Ensure you are on the branch where you want to squash commits: Make sure you are on the branch where you want to squash the commits.
bashgit checkout <your-branch-name>
Start Interactive Rebase: Run the following command to start an interactive rebase:
bashgit rebase -i HEAD~n
Replace n
with the number of commits you want to squash. For example, if you want to squash the last 3 commits, use git rebase -i HEAD~3
.
An Editor will open: Git will open an interactive rebase file in your default text editor. It will look something like this:
bashpick abc123 Commit message 1 pick def456 Commit message 2 pick ghi789 Commit message 3
Change pick
to squash
(or just s
for short) for the commits you want to squash. For example:
bashpick abc123 Commit message 1 squash def456 Commit message 2 squash ghi789 Commit message 3
Save and close the file.
Edit the Commit Message: Another editor will open for you to edit the commit message. You can keep the existing messages or combine them into a new one. Save and close the file.
Finish the Rebase: Finish the rebase with the following command:
bashgit rebase --continue
Force Push: Since you have rewritten the commit history, you'll need to force push the changes to the remote repository. Use the following command:
bashgit push origin <your-branch-name> --force
Note: Be cautious when force pushing, especially if others are collaborating on the same branch, as it can disrupt their work. Only force push if you are sure it won't cause issues for your collaborators.
That's it! You've successfully squashed multiple commits into one.