Skip to main content

Git Rebase Onto Main (Full Guide, No Fluff)

· 3 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

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