Step-by-Step guide to Squashing multiple commits into a single commit in GIT
When working on a coding project, there might be times where you end up making multiple commits for a single feature request. In order to keep the commits clean and tidy, developers often wish to squash all these commits into one single commit. Here is a step-by-step guide to merging multiple commits into a single commit in Git, commonly referred to as "squashing" commits.
Step 1: Set Up Your Repository
mkdir squash-commit-demo
cd squash-commit-demo
git init
Create a File and Make an Initial Commit
echo "Initial content" > file.txt
git add .
git commit -m "Initial commit"
Step 2: Create multiple Commits
Make Changes and Commit Multiple Times
echo "Change 1" >> file.txt
git add .
git commit -m "Add change 1"
echo "Change 2" >> file.txt
git add .
git commit -m "Add change 2"
echo "Change 3" >> file.txt
git add .
git commit -m "Add change 3"
Step 3: Squash Commit into a single Commit
Check Commit History
Verify the commit history before squashing
git log --oneline
You should see something like
Start an Interactive Rebase
To squash the last three commits into a single commit
git rebase -i HEAD~3
This command opens an interactive rebase editor with the last three commits.
Modify the Interactive Rebase Editor
The editor will show something like
Change the second and third commits from pick to squash (or s) as shown below
Save and close the editor.
Edit Commit Message
The editor will re-open for you to combine commit messages. Modify it as needed
Modify the commit message to something concise
Consolidate changes 1, 2, and 3
Save and close the editor
Step 6: Verify the Squash
Check the Commit History
git log --oneline
git log --oneline --graph
cat file.txt
Verify that the commits have been squashed into one.
You should also see all the 3 changes in the file.
Summary
You've successfully squashed multiple commits into a single commit. The key steps involved making multiple commits, starting an interactive rebase, modifying the rebase editor to squash commits, editing the commit message, and verifying the changes.
Additional Tips
Interactive Rebase Options:
pick
orp
: Use the commit.squash
ors
: Combine commit with the previous commit, retaining commit message.fixup
orf
: Combine commit with the previous commit, discarding commit message.
Automating Squashes:
You can also use
git reset --soft
to undo commits and then create a single commit, but this method rewrites history and should be used with caution, especially for shared branches.git reset --soft HEAD~3 git commit -m "Consolidate changes 1, 2, and 3"
Rewriting History:
- Squashing commits rewrites history, so it's generally recommended for local branches or before sharing branches with others.
That's all for today. Kindly share with the community.
Subscribe to my newsletter
Read articles from ferozekhan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by