Sub topic 13
Rebasing a branch onto another
This chapter assumes you can create branches, make commits, and merge them. It also assumes you know what HEAD is and how a branch points at a commit. You need Git 2.28 or later to run the demo script as written, because it uses git init -b.
What rebase does
A merge joins two lines of work by adding a commit with two parents. A rebase moves your branch instead. It takes the commits that are on your branch but not on the target branch, and replays them one at a time on top of the target's tip. Afterwards your branch looks as if you had started it from the newer commit.
Suppose main moved on after you created feature/login.
After git rebase main on feature/login, the history is a straight line.
C' and D' are new commits. They contain the same changes as C and D, but they have a different parent. A commit's ID is a hash that covers its parent, so each copy gets a different ID. Rebasing therefore rewrites history. The original C and D still exist in the object database, but no branch points to them.
Running a rebase
This script builds a small repository with the diverged shape from the diagram. It then rebases the feature branch.
set -e
git init -b main rebase-demo
cd rebase-demo
git config user.name "Demo"
git config user.email "[email protected]"
echo a > a.txt && git add a.txt && git commit -m "A"
echo b > b.txt && git add b.txt && git commit -m "B"
git switch -c feature/login
echo c > c.txt && git add c.txt && git commit -m "C"
echo d > d.txt && git add d.txt && git commit -m "D"
git switch main
echo e > e.txt && git add e.txt && git commit -m "E"
git log --oneline --graph --all
git switch feature/login
git rebase main
git log --oneline --graph --allThe first graph shows two lines that split at B. The second shows one line: A, B, E, C', D'. Your hashes will differ from anyone else's, and the hashes of C and D change after the rebase.
The command form is git rebase <upstream>, run while the branch to move is checked out. Git finds the commits reachable from HEAD but not from <upstream>, saves them as patches, resets the branch to <upstream>, and applies the patches in order.
After the rebase, main can fast-forward to feature/login. A fast-forward merge needs no merge commit and leaves a linear history.
git switch main
git merge feature/loginConflicts during a rebase
Git replays commits one at a time, so a conflict stops the rebase at the commit that failed. You may have to resolve conflicts several times, once per conflicting commit.
- Open the files with
<<<<<<<,=======, and>>>>>>>markers and edit them into the result you want. - Stage the files with
git add. - Run
git rebase --continue. Do not rungit commit, because Git creates the commit itself.
git rebase main
# CONFLICT in c.txt
# edit c.txt, then:
git add c.txt
git rebase --continue
# other options while stopped:
git rebase --skip # drop the current commit entirely
git rebase --abort # return to the state before the rebase beganDuring a rebase, HEAD is detached while Git applies commits. Git also swaps the meaning of the two sides. In conflict tools, "ours" (the HEAD side) is the branch you are rebasing onto, and "theirs" is your own commit being replayed. This surprises many people who are used to merges, where "ours" is your branch.
A git status mid-rebase shows rebase in progress and lists the remaining steps. If you lose track, git rebase --abort is a safe way out.
Pushing a rebased branch
If you had already pushed feature/login, the remote branch holds C and D, and your local branch holds C' and D'. A plain git push is rejected because the histories diverged. You must replace the remote branch.
git switch feature/login
git rebase main
git push --force-with-lease--force-with-lease refuses to overwrite the remote branch if it contains commits you have not fetched. A teammate may have pushed to it since your last fetch. A plain --force would discard their work without any warning.
--force-with-lease is only as safe as your last fetch. If an editor or tool runs git fetch in the background, Git may think you have already seen a teammate's commit. Run git fetch yourself and read what came in before you force-push.
Moving a branch with --onto
Sometimes you want to change the starting point of a branch to something other than its upstream. Say feature/ui was started from feature/login, and feature/login is going to be squashed or rewritten. You want feature/ui to be based on main instead, without dragging along the login commits.
git rebase --onto main feature/login feature/uiRead this as "take the commits after feature/login up to feature/ui, and replay them onto main". The three arguments are the new base, the old base, and the branch to move.
Cleaning up commits with interactive rebase
git rebase -i opens an editor with a list of the commits to replay. You change the word at the start of each line to choose what happens to it.
git rebase -i main| Command | Effect |
|---|---|
| `pick` | Keep the commit as it is |
| `reword` | Keep the changes and edit the message |
| `squash` | Fold into the previous commit and combine the messages |
| `fixup` | Fold into the previous commit and discard this message |
| `drop` | Remove the commit |
You can also reorder commits by moving lines. If you delete all lines, or leave the file empty, Git aborts the rebase. This is how many teams tidy a branch of "wip" and "fix typo" commits before review.
Undoing a rebase
Rebase does not destroy the old commits right away. Git records where your branch pointed before the rebase started, and ORIG_HEAD holds that value right after the rebase finishes.
git reset --hard ORIG_HEADORIG_HEAD is overwritten by later operations such as another reset or merge. A more durable way is the reflog.
git reflog feature/login
git reset --hard feature/login@{1}Use the reflog to find the entry from just before the rebase. git reset --hard discards uncommitted changes, so commit or stash them first.
Common errors
- "Cannot rebase: You have unstaged changes." Rebase needs a clean working tree. Commit or stash your changes, or run
git rebase --autostash. - The rebase seems to replay commits you did not write. You may have rebased onto the wrong branch, or
mainlocally is out of date. Rungit fetchand rebase ontoorigin/main. - Push is rejected after a rebase. This is expected, since the commit IDs changed. Use
git push --force-with-leaseonly on a branch you own. - The same conflict appears at every step. Several of your commits touch the same lines. Consider squashing them with
git rebase -ifirst, so you resolve the conflict once. - You resolved a conflict and ran
git commit. Git may end up with a confusing state. Rungit statusto see where you are and finish withgit rebase --continue.
Exercise
You rebased feature/login onto main and then ran git push. Git rejected the push. Why, and what is the safest command to use next?
Show answer
The rebase created new commits (C' and D') with different IDs, so the remote branch and your local branch have diverged, and Git refuses a push that is not a fast-forward. Run git fetch and look at what, if anything, is new on the remote branch. Then run git push --force-with-lease, which overwrites the remote branch only if it still holds the commits you last fetched.
Exercise
Midway through git rebase main, Git stops with a conflict. You fix the file and run git add on it. What do you run next, and what do you run if you decide to give up?
Show answer
Run git rebase --continue to record the commit and replay the next one. To give up, run git rebase --abort, which returns the branch to its state before the rebase began.