Sub topic 5
Rebasing a feature branch onto the latest main
This chapter assumes you can add, commit, branch, switch, and push. It also assumes you can read git log output and know what a remote branch such as origin/main is.
Why rebase onto main
While you work on feature, other people add commits to main. Your branch still starts from the old tip of main. Rebasing moves the start of your branch to the new tip. Git takes the commits that exist only on feature and replays them on top of the latest origin/main. The result is a straight line of history with no merge commit.
In the diagram, D' and E' are copies of D and E. Their content changes are the same, but they have new parents, so they get new hashes.
The steps
- Switch to the branch you want to move.
- Fetch the latest remote state.
- Rebase onto the updated remote branch.
git switch feature
git fetch origin
git rebase origin/mainRebase onto origin/main, not local main. Local main can be out of date, and git fetch updates origin/main without touching your working branch.
If there are no conflicts, Git replays each commit and prints a success message. Check the result:
git log --oneline --graph --decorate -n 8Your feature commits now sit directly above the tip of origin/main.
What if Git stops
If two changes touch the same lines, Git pauses and reports a conflict. You then fix the files, stage them, and continue, or abort. The next chapter covers that loop in detail. If you want to leave right now, run git rebase --abort. It restores the branch to its state before the rebase.
Common errors
- Rebasing the wrong branch. Run
git statusfirst. The rebase moves the branch you are on. - Skipping the fetch. Without it, you rebase onto a stale
origin/main. - Uncommitted changes. Git may refuse to start, or the rebase may be harder to undo. Commit or stash first.
- Push rejected afterward. If
featurewas already pushed, its history has changed. A normalgit pushfails. Pushing rewritten history needs care, and a later chapter explains it.
Exercise
You are on feature and origin/main has new commits. Which commands bring those commits under your branch, and why rebase onto origin/main rather than main?
Show answer
Run git fetch origin, then git rebase origin/main. Fetch updates origin/main to the latest remote state. Local main may be stale, so rebasing onto it could leave your branch behind.