🔹 Step-by-step (squash your 5 commits into 1)
1. Go to your branch
git checkout your-feature-branch
2. Start interactive rebase (last 5 commits)
git rebase -i HEAD~5
3. You’ll see something like:
pick a1b2c3 add login UI
pick b2c3d4 fix bug
pick c3d4e5 update API
pick d4e5f6 fix typo
pick e5f6g7 refactor code
4. Change it to:
👉 Keep first as pick, rest as squash (or s)
pick a1b2c3 add login UI
squash b2c3d4 fix bug
squash c3d4e5 update API
squash d4e5f6 fix typo
squash e5f6g7 refactor code
5. Save & close editor
Git will now ask for a final commit message
Replace with something clean:
Add login UI with API integration, bug fixes, and refactoring
6. Done 🎉
Now all 5 commits = 1 commit
🔹 Important (don’t skip this)
If your branch is already pushed to remote:
git push --force
⚠️ This rewrites history—only do this on your feature branch, not shared branches like main.
🔹 Shortcut (if you don’t care about messages)
You can also do:
git reset --soft HEAD~5
git commit -m "Add login feature with all fixes"
🔹 Pro tip (real-world)
- Use rebase squash → before PR
- Use Squash & Merge → during PR
- Avoid messy commits in
main
If you want next level:
I can show how companies enforce this using Git hooks / CI rules (very useful for team lead role).
Got it—you’re asking what this actually means 👇
git reset --soft HEAD~5
git commit -m "Add login feature with all fixes"
🔹 Simple Meaning
👉 This is a shortcut way to squash commits into one
Instead of using rebase -i, this does:
- Go back 5 commits
- Keep all changes in staging
- Create 1 new commit
🔹 Step-by-step explanation
✅ git reset --soft HEAD~5
👉 Break it down:
HEAD~5= go back 5 commitsreset= move branch pointer backward--soft= DO NOT delete changes, keep them staged
So after this command:
✔ All 5 commits are removed
✔ But their code changes are still there
✔ And already staged (ready to commit)
✅ git commit -m "..."
Now you create one new clean commit:
Add login feature with all fixes
🔹 Visual understanding
Before:
commit1 -> commit2 -> commit3 -> commit4 -> commit5 (HEAD)
After reset:
(no commits)
but all changes are staged
After new commit:
single commit (combined work)
🔹 Key difference vs rebase
| Method | Control | Use case |
|---|---|---|
rebase -i | Full control | Best for clean history |
reset --soft | Quick & simple | Fast squash |
🔹 Important warning ⚠️
If already pushed:
git push --force
Otherwise remote will still have old commits.
🔹 One-line understanding
👉 git reset --soft HEAD~5 = remove last 5 commits but keep their changes staged
If you want, I can explain:
- difference between
--soft,--mixed,--hard(very important for interviews)
No comments:
Post a Comment