This guide provides a solution for users who need to combine (squash) multiple commits into a single one after they have already been pushed to a remote repository.
Important: Rebasing pushed commits changes the history. Do not follow this guide if you are working on a shared branch that others have pulled from, as it will break their history.
Before anything else, here's the part that I always rely on, so I will just copy and paste it, then explain it;
Squash commits on the remote with:
git rebase -i origin/master~4 masterwhere ~4 means the last 4 commits.
and then force push with :
git push origin +masterOpen your terminal and run the rebase command. Replace N with the number of commits you want to review (e.g., 4 for the last 4 commits).
git rebase -i HEAD~N
# Or targeting a specific branch
git rebase -i origin/masterYour default text editor will open with a list of commits.
- Keep the first commit as pick.
- Change the commands for the subsequent commits you want to combine from pick to squash (or s).
pick 1fc6c95 New feature A
squash 6b2481b Fix typo in A
squash dd1475d Fix bug in A
- Save and close the file.
A new editor window will open allowing you to modify the commit message for the new combined commit. Edit the message as desired, then save and close.
Since you have rewritten the history, a standard push will fail. You must force push the changes to the remote.
# Using + syntax (safer, only forces the specific branch)
git push origin +master
# Or using the force flag
git push --force origin masterSource: StackOverflow