Squash Commits
To combine multiple Git commits into one (known as "Squash Commits"), you can use git rebase -i (interactive rebase). This keeps the Git history cleaner by merging several commits. Here's how:
Steps to Squash Commits:
1. Start an interactive rebase:
Decide how many commits you want to squash, then run:
git rebase -i HEAD~N
Replace N with the number of commits to go back. For example, to squash the last 3 commits, use HEAD~3.
2. Edit commits in the interactive rebase:
A text editor will open, showing a list of the last N commits:
pick abcdef1 First commit message
pick abcdef2 Second commit message
pick abcdef3 Third commit message
Change pick to squash (or s) for the commits you want to combine, leaving the first commit as pick:
pick abcdef1 First commit message
squash abcdef2 Second commit message
squash abcdef3 Third commit message
3. Execute the rebase:
Save and close the editor. Git will squash the commits. A new editor will open, where you can modify the commit message. You can keep the existing messages or write a new one.
4. Complete the rebase:
After the rebase finishes, push the changes. If you've already pushed, force-push the new history:
git push --force
Note: Be cautious with git push --force-with-lease, especially if others are working on the same branch, as it rewrites history.
Summary:
Use git rebase -i HEAD~N to start an interactive rebase.
Change pick to squash for the commits you want to merge.
Edit the commit message if necessary.
Force-push with git push --force-with-lease to update the remote.
This method cleans up the Git history by merging multiple commits into one.