Squashing Git commits is a technique used to combine multiple commits into a single, more meaningful commit. This can help keep your Git history clean and concise. Here are the steps to squash Git commits:
-
Identify the Commits to Squash:
- First, you need to identify the range of commits you want to squash. Typically, you'll want to squash the most recent commits.
-
Open Your Terminal:
- Open a terminal or command prompt.
-
Checkout the Branch:
- Ensure you are on the branch where you want to squash the commits. You can switch to the branch using the
git checkout branch-namecommand.
- Ensure you are on the branch where you want to squash the commits. You can switch to the branch using the
-
Start an Interactive Rebase:
- Use the following command to start an interactive rebase for the last n commits (replace n with the number of commits you want to squash):
shellCopy codegit rebase -i HEAD~nFor example, if you want to squash the last three commits, you would run:
shellCopy codegit rebase -i HEAD~3This will open an editor with a list of commits in your text editor.
-
Squash Commits:
- In the text editor, you'll see a list of commits with the word "pick" in front of each commit message. To squash commits, change the word "pick" to "squash" (or just "s" for short) for the commits you want to squash. Leave the word "pick" for the commit you want to retain as the final commit.
Example:
shellCopy codepick abc123 First commit squash def456 Second commit squash 789xyz Third commit -
Save and Close the Editor:
- Save the changes and close the text editor.
-
Edit the Combined Commit Message:
- Git will open another text editor for you to edit the commit message of the combined commit. Here, you can modify the commit message if needed. Once you're satisfied with the message, save and close the editor.
-
Finish the Rebase:
- After you've saved the combined commit message, the rebase is complete. Git will apply the changes, and you'll have a single squashed commit with a new commit message.
-
Push the Changes:
- If you've pushed the branch to a remote repository previously, you'll need to force-push the changes to the remote branch since you've rewritten the commit history. Use the following command:
shellCopy codegit push origin branch-name --force
Please be cautious when using --force because it can overwrite the remote branch's history, potentially causing issues for collaborators. Make sure to communicate with your team if you're working in a shared repository.