How to Rebase Onto Main in Git: Simple Steps
To rebase your current branch onto
main in Git, use git fetch to update remote branches, then run git rebase origin/main. This moves your commits on top of the latest main branch, keeping history clean.Syntax
The basic command to rebase your current branch onto main is:
git fetch: Updates your local copy of remote branches.git rebase origin/main: Reapplies your commits on top of the latestmainbranch from the remote.
bash
git fetch git rebase origin/main
Example
This example shows rebasing a feature branch onto the latest main branch from the remote repository.
bash
$ git checkout feature-branch $ git fetch $ git rebase origin/main # If there are conflicts, resolve them, then run: $ git rebase --continue # After successful rebase, push with force to update remote feature branch: $ git push --force-with-lease
Output
First, you switch to your feature branch.
Fetching updates from remote.
Rebasing your commits on top of origin/main.
If conflicts occur, Git pauses and asks you to fix them.
After fixing, you continue the rebase.
Finally, you update the remote branch with your rebased commits.
Common Pitfalls
Common mistakes when rebasing onto main include:
- Not running
git fetchfirst, so you rebase onto an outdatedmain. - Forgetting to resolve conflicts properly during rebase.
- Using
git pushwithout--force-with-leaseafter rebasing, which can cause push errors. - Rebasing public branches shared with others, which can confuse collaborators.
bash
Wrong way: $ git rebase main # This rebases onto your local main, which may be outdated. Right way: $ git fetch $ git rebase origin/main # Rebases onto the latest remote main branch.
Quick Reference
| Command | Purpose |
|---|---|
| git fetch | Update remote tracking branches |
| git rebase origin/main | Rebase current branch onto latest remote main |
| git rebase --continue | Continue rebase after resolving conflicts |
| git push --force-with-lease | Push rebased branch safely to remote |
Key Takeaways
Always run git fetch before rebasing to get the latest main branch.
Use git rebase origin/main to move your commits on top of the updated main.
Resolve conflicts carefully and use git rebase --continue to proceed.
After rebasing, push with --force-with-lease to update the remote branch safely.
Avoid rebasing branches that others are using to prevent confusion.