To combine commits in Git, you can use the interactive rebase feature. Here’s how to do it step-by-step:
Steps to Combine Commits
-
Start Interactive Rebase: Determine how many commits back you want to combine. For example, if you want to combine the last three commits, run:
git rebase -i HEAD~3 -
Choose Commits to Combine: This command will open a text editor showing the last three commits. It will look something like this:
pick abc1234 Commit message 1 pick def5678 Commit message 2 pick ghi9101 Commit message 3To combine commits, change
picktosquash(ors) for the commits you want to merge into the previous commit. For example:pick abc1234 Commit message 1 squash def5678 Commit message 2 squash ghi9101 Commit message 3 -
Save and Exit: Save the changes and close the editor. Git will combine the specified commits into the first one.
-
Edit Commit Message: After combining, Git will open another editor window to allow you to edit the commit message for the combined commit. You can keep, modify, or create a new message.
-
Finish the Rebase: Save the commit message and close the editor. The rebase will complete, and the commits will be combined.
Important Note
When combining commits, be cautious if the commits have already been pushed to a shared repository, as this rewrites history and can cause issues for collaborators.
Summary
To combine commits, use interactive rebase to select the commits you want to merge, change pick to squash for the desired commits, edit the commit message, and finish the rebase.
