Git Rebase Onto Main (Full Guide, No Fluff)
ยท 4 min read
You want to bring your feature branch up to date with the latest main, but you donโt want messy merge commits.
The solution: rebase.
Rebase reapplies your local commits on top of the latest main from remote. It keeps your commit history clean, linear, and easy to read - especially when preparing a pull request.
โ TL;DRโ
git fetch origin
git rebase origin/main
git push --force-with-lease
๐ ๏ธ Step-by-Step: Rebase Onto Mainโ
Switch to your feature branch (if you arenโt already)โ
git switch your-branch-name
Fetch the latest remote branchesโ
git fetch origin
This ensures you have the latest version of origin/main locally.
Rebase your current branch onto mainโ
git rebase origin/main
This will take your local commits and reapply them on top of the latest commits in main.
โ๏ธ If There Are Conflictsโ
Youโll see output like:
CONFLICT (content): Merge conflict in example.py
Hereโs what to do:
1. Manually fix the conflicting file(s)
Open the files, look for conflict markers like <<<<<<<, =======, and >>>>>>>, and clean it up.
2. Mark the files as resolved
git add path/to/conflicted_file
3. Continue the rebase process
git rebase --continue
Repeat this cycle (fix โ add โ continue) until the rebase is done.
๐ Abort the Rebase (If You Need To)โ
If something goes wrong and you want to cancel everything and go back to how it was before the rebase started:
git rebase --abort
This restores your branch to its previous state before the rebase attempt.
๐ Push Your Changes (Force Required)
After a successful rebase, your local commit history has changed. Git will reject a normal push.
Instead, do:
git push --force-with-lease
๐ Use --force-with-lease instead of --force.
Itโs safer - it will refuse to push if someone else updated the remote branch since you last pulled.
๐ก Why Rebase Instead of Merge?
No clutter from extra merge commits
Clean, linear commit history
Easier git log, git blame, and git bisect
Ideal for pull requests: your commits appear as if they happened after main
Helps reviewers follow your changes without distractions
๐ง Final Summaryโ
Hereโs your copy-paste cheat sheet:
# Step into your feature branch
git switch my-feature-branch
# Get the latest remote state
git fetch origin
# Reapply your commits onto the latest main
git rebase origin/main
# If conflicts happen:
# fix them manually
# git add .
# git rebase --continue
# If something breaks:
# git rebase --abort
# Push your changes after rebase (you must force)
git push --force-with-lease
