git command to squash commits
- dheeraj moolya
- Oct 21, 2024
- 2 min read
Squashing Commits with Git Rebase
Identify the Commits to Squash: Determine how many commits you want to squash. For example, if you want to squash the last 3 commits.
Start the Interactive Rebase: Use the following command:
git rebase -i HEAD~3
This command opens an interactive rebase session for the last 3 commits.
Modify the Commit List: In the text editor that opens, you’ll see a list of the last 3 commits. It will look something like this:
pick abc123 Commit message 1
pick def456 Commit message 2
pick ghi789 Commit message 3
Change the word pick to squash (or s) for the commits you want to squash into the first one:
pick abc123 Commit message 1
squash def456 Commit message 2
squash ghi789 Commit message 3
Save and Exit the Editor: After making the changes, save the file and exit the editor. This will start the rebase process.
Edit the Commit Message: Another editor will open, allowing you to modify the commit message for the squashed commits. You can keep the original messages, combine them, or write a new one.
Complete the Rebase: Save and exit the editor to complete the rebase.
Important Notes:
Backup Your Branch: It's a good idea to create a backup of your branch before rebasing, especially if you’re working on a shared branch. You can do this by creating a new branch:
git checkout -b backup-branch
Force Push After Squashing: If you’ve already pushed the commits to a remote repository, you will need to force push the changes:
git push origin your-branch-name --force
Squashing commits is a great way to clean up your commit history before merging changes into the main branch!
Comments