0
0
GitHow-ToBeginner · 3 min read

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 latest main branch 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 fetch first, so you rebase onto an outdated main.
  • Forgetting to resolve conflicts properly during rebase.
  • Using git push without --force-with-lease after 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

CommandPurpose
git fetchUpdate remote tracking branches
git rebase origin/mainRebase current branch onto latest remote main
git rebase --continueContinue rebase after resolving conflicts
git push --force-with-leasePush 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.