[Git] Rebase a branch onto another with git rebase
You can use git rebase to replay commits from your current branch on top of another branch's latest commit. This is helpful when you want to incorporate updates from remote main or master while keeping a linear history on your feature branch.
Rebase onto the remote main branch
If your remote is named origin, you can fetch origin/main and rebase feature onto it.
git checkout feature
git fetch origin
git rebase origin/main
For example, if origin/main and feature diverged at commit B, the history looks like this before and after the rebase. Commits grow newer from left to right.
origin/main still points at D. The changes from E and F are replayed after D as new commits E' and F' with different commit IDs.
When the rebase finishes, you may see:
Successfully rebased and updated refs/heads/feature.
If feature is already based on the tip of origin/main, Git may print Current branch feature is up to date. You can also rebase onto your local main with git rebase main.
When a conflict occurs
If the rebase stops, edit the conflicted files, git add the resolved paths, and run git rebase --continue. For example, after fixing README.md:
git add README.md
git rebase --continue
Repeat the same steps if another commit conflicts. To abort and return to the state before the rebase, run git rebase --abort.
Rebase versus merge
Rebased commits get new IDs. If you have already pushed feature and others use it, git merge can integrate main without rewriting shared commits.
git checkout feature
git fetch origin
git merge origin/main
A plain git pull may perform a rebase depending on your configuration. If feature tracks origin/feature, git pull --rebase with no extra arguments rebases onto origin/feature.
References
- Git - git-rebase Documentation: https://git-scm.com/docs/git-rebase
- Git - git-pull Documentation: https://git-scm.com/docs/git-pull