Git Rebase: A Powerful Way to Rewrite Commit History
Git rebase is a way to rewrite commit history by moving or modifying commits. It is often used to:
1. Understanding Rebase vs. Merge
Merge (git merge)
- Creates a new "merge commit" that combines branches.
- Preserves the history of both branches.
- Can lead to a messy commit history with many merge commits.
Rebase (git rebase)
- Moves or reapplies commits on top of another branch.
- Keeps history linear and clean.
- Avoids unnecessary merge commits.
Example:
git checkout feature-branch git rebase main
š¹ This moves all commits from feature-branch to the latest main.
2. Using Git Rebase
2.1 Rebasing a Feature Branch onto Main
If your feature-branch is behind main and you want to bring in the latest changes:
git checkout feature-branch git rebase main
š¹ This moves the commits from feature-branch on top of main.
If conflicts occur, resolve them and continue with:
git rebase --continue
To abort the rebase and go back:
git rebase --abort
3. Interactive Rebase (git rebase -i)
Interactive rebase lets you edit, reorder, squash, or remove commits.
3.1 Start an Interactive Rebase
git rebase -i HEAD~3
š¹ This allows you to modify the last 3 commits.
You'll see a list like this:
pick a1b2c3 First commit
pick d4e5f6 Second commit
pick g7h8i9 Third commit
3.2 Modify Commits
Replace pick with:
- reword→ Edit commit message
- edit→ Modify the commit
- squash→ Merge commits
- drop→ Delete the commit
Example (squashing commits):
pick a1b2c3 First commit
squash d4e5f6 Second commit
pick g7h8i9 Third commit
š¹ This combines the Second commit into the First commit.
After saving, Git will prompt you to update the commit message.
4. Rebasing a Remote Branch
4.1 Force Push After Rebase
Since rebase rewrites history, you must force push:
git push --force
For a safer force push:
git push --force-with-lease
š¹ This prevents overwriting commits if someone else pushed changes.
5. Undoing a Rebase
If something goes wrong during rebase:
git reflog git reset --hard ORIG_HEAD
š¹ This restores your branch to before the rebase.
Conclusion
| Action | Command | 
|---|---|
| Rebase feature branch onto main | git rebase main | 
| Start interactive rebase (last 3 commits) | git rebase -i HEAD~3 | 
| Squash commits during rebase | Change picktosquash | 
| Undo a rebase | git reset --hard ORIG_HEAD | 
| Continue after fixing conflicts | git rebase --continue | 
| Abort rebase | git rebase --abort | 
š¹ Use git rebase to keep a clean commit history! Would you like a more detailed example? š

