Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 78 ยท Rewriting History

Rebasing

Learn git rebase step by step: replay commits onto a new base, compare it with merge, use --onto, resolve conflicts, pull --rebase, autosquash and follow the golden rule.

You started a feature branch last week. Since then, main has moved on with other people's commits. You want your work to sit on top of the latest main, as if you had started today. You can merge main into your branch, which adds a merge commit. Or you can rebase your branch onto main, which replays your commits on top of the new tip and leaves a straight line of history.

This lesson explains what rebase really does (it creates new commits, it does not move old ones), how to run it, how to handle conflicts, --onto for surgical moves, pull --rebase, --autosquash, and the one rule you must remember: never rebase commits other people already have.

What rebase does

Suppose feature branched from commit B on main, and main has since gained M1 and M2:

TEXT
Before:
            F1---F2   feature
           /
  A---B---M1---M2     main

After  git switch feature && git rebase main:

                      F1'--F2'   feature
                     /
  A---B---M1---M2     main

Git finds the commits that are on feature but not on main (F1, F2), sets them aside, moves feature to the tip of main, and then re-applies each change in turn. The new commits F1' and F2' have the same changes and messages, but a different parent, so they have different hashes. The old F1 and F2 are no longer on any branch (the reflog still remembers them).

Bash Rebase a feature branch onto a moved main

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The graph before shows two diverging lines. After the rebase there is one straight line A, B, M1, M2, F1, F2, and feature is simply ahead of main. Compare the hashes of F1 and F2 before and after: they changed. That is the key fact to remember. Rebase rewrites history.

Rebase versus merge

Both integrate work from one branch into another. They record it differently.

TEXT
merge main into feature:               rebase feature onto main:

        F1---F2--M                          M1---M2---F1'--F2'
       /        /                          /
  A---B---M1---M2                     A---B
Merge Rebase
History shape real branching and joining a straight line
Extra commit yes, a merge commit no
Existing commits unchanged replaced by new copies
Safe on shared branches yes no
Conflicts resolved once resolved once per replayed commit, as needed
Tells the true story of when work happened yes no, it looks sequential

Neither is "better". Teams choose one for their workflow: merge keeps an exact record, rebase keeps a readable one. A common compromise is to rebase your private branch to stay current and to clean it up, then merge it into main with --no-ff or a squash (see Merging Branches).

If the branch can simply be fast-forwarded, rebase and merge produce the same result. Rebase only becomes visible when both sides have new commits.

The golden rule

Never rebase commits that exist outside your own repository.

Rebase replaces commits. If a teammate already pulled F1 and F2, their history contains the old commits. When you push the rewritten branch, Git sees two different versions of the "same" work. They then have to untangle duplicated commits and conflicts. The fix is easy to say and annoying to do, so avoid it: rebase local or private branches only. After you have pushed and shared a branch, switch to merge or git revert.

It is fine to rebase a branch you have pushed if you are the only person using it (a typical pull-request branch), as long as you know a force push is needed afterwards and use --force-with-lease. See push, pull and Tracking Branches.

Conflicts during a rebase

Each commit is re-applied as a small merge. If the change conflicts with something already on the new base, Git stops in the middle and tells you which commit it was applying. You fix the file, git add it, and tell Git to carry on. You have three escape hatches:

Command Meaning
git rebase --continue I resolved the conflict and staged the files; apply the next commit
git rebase --skip drop the commit that is conflicting; move on
git rebase --abort forget everything and go back to how it was before the rebase

--abort is always safe: nothing is lost. Conflict markers during a rebase confuse people because the sides are reversed compared with a merge: HEAD (the "ours" side) is the branch you are rebasing onto, and "theirs" is your own commit that is being replayed.

Bash A rebase that stops on a conflict, resolved and continued

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

During the stop, git status reports that you are in the middle of a rebase. The app.txt file contains <<<<<<< HEAD with the main wording on top and the replayed commit's text (labelled with its message, Feature title) below. After git add and --continue, the rest of the commits (here Add extra) were applied without trouble. Every conflict you resolve belongs to one particular commit, which makes rebase conflicts smaller than one big merge conflict. The resolution for a repeated conflict can also be remembered with git config rerere.enabled true (see Resolving Merge Conflicts).

Rebase --onto: moving a range of commits

git rebase main is shorthand. The full form is git rebase --onto <newbase> <upstream> <branch> and reads: take the commits that are in <branch> but not in <upstream>, and replay them on <newbase>. It is how you transplant part of a branch.

A classic case: you branched topic from feature, but feature is not ready, and topic should go to main on its own.

TEXT
Before:
  A---B---C  main
       \
        F1---F2  feature
                \
                 T1---T2  topic

git rebase --onto main feature topic

After:
  A---B---C---T1'--T2'  topic
   (main is at C)
       \
        F1---F2  feature
Bash Move topic off feature and onto main with --onto

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

After the command, topic contains T1 and T2 on top of C and does not have F1 or F2 (see the file list), while feature is unchanged. Note that git rebase --onto main feature topic also checks out topic first.

Pull with rebase

git pull is git fetch followed by a merge. When your local branch has commits and the remote also moved, a plain pull creates a merge commit titled "Merge branch 'main' of ...". Many people dislike those. git pull --rebase fetches and then rebases your local commits on top of the fetched ones:

TEXT
git pull --rebase
git config --global pull.rebase true     # make it the default
git config --global rebase.autoStash true  # stash/unstash dirty files around the rebase

You can try the effect with a local "remote". Here a bare repository stands in for a server (more in Remotes). Two people commit to the same branch, and the second pulls with rebase.

Bash pull --rebase keeps history linear

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Alice's local commit now sits on top of Bob's, with no merge commit. When her branch is later pushed, it is a plain fast-forward for the server. Because she rebased only commits that had never been pushed, the golden rule was respected.

Autosquash, and what comes next

During work you often make a small correction to a commit that is already several steps back. git commit --fixup=<commit> creates a commit named fixup! <original subject>. When you later run git rebase -i --autosquash, Git automatically moves each fixup directly under its target and marks it for squashing. This turns messy work into a clean story. Because -i opens an editor, scripts and our sandbox set GIT_SEQUENCE_EDITOR=:, which accepts the prepared plan without asking. The next lesson, Interactive Rebase, covers the full toolbox (reword, edit, squash, drop, exec).

Bash Fixup and autosquash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The fixup commit disappeared. Its change was folded into Add a, and Add b stayed on top, so the history reads as if the typo had never existed.

Useful options and safety habits

  • git rebase main rebases the current branch. git rebase main feature first switches to feature.
  • git rebase --abort returns you to the state before the rebase. Use it freely.
  • git rebase --rebase-merges keeps merge commits instead of flattening them.
  • git rebase -x "make test" runs a command after each replayed commit, to verify that every commit builds.
  • git rebase --keep-base and git rebase --root exist for special cases (the second replays everything, including the first commit).
  • After a rebase, git reflog or ORIG_HEAD returns you to the old tip: git reset --hard ORIG_HEAD (git reset in Depth).
  • git range-diff main@{1} main feature compares two versions of a branch commit by commit (see Comparing Commits, Branches and Files).
  • Before rebasing a big branch, make a safety bookmark: git branch backup/feature.

Do not rebase a branch that other people have based work on, and do not rebase main. If you rebase a branch you have already pushed, the push is rejected as a non-fast-forward. Use git push --force-with-lease (never plain --force), which refuses if someone else pushed in the meantime.

When to rebase, when to merge

Rebase when you want to update a private branch with the latest main, clean up before review (squash fixups, reword messages), or keep the project history linear by team rule. Merge when the branch is shared, when you need a record that the work was developed in parallel, or when you are integrating a long-lived branch into main. If in doubt, merge: it never destroys information.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to your commits when you run git rebase main on a feature branch?

    Rebase replays each commit's changes on a new parent, which produces new commit objects with different hashes. The old commits stay in the reflog until garbage collection.
  2. 2. What is the golden rule of rebasing?

    Rebased commits replace the originals. If others based work on the originals, their history and yours diverge.
  3. 3. You are halfway through a rebase and the conflicts are a mess. How do you return to the state before you started?

    git rebase --abort restores the branch to its position before the rebase. --skip would drop the current commit and continue.
  4. 4. What does git rebase --onto main feature topic do?

    The form is --onto newbase upstream branch: the commits in branch that are not in upstream are replayed on newbase.
  5. 5. What is git pull --rebase useful for?

    pull --rebase is fetch plus rebase. Your unpushed commits are re-applied on the updated remote branch.

Summary

  • Rebase replays your commits onto a new base. The copies have new hashes, and the old ones are abandoned.
  • The result is a straight history without merge commits; merge keeps the real branching and never rewrites anything.
  • Never rebase commits that are shared. Private branches are fair game.
  • On a conflict, fix the files, git add them and git rebase --continue; --skip drops the commit and --abort undoes the whole rebase. Ours and theirs are swapped compared with merge.
  • git rebase --onto newbase upstream branch moves a range of commits to a different base.
  • git pull --rebase avoids needless merge commits, and git commit --fixup with rebase -i --autosquash folds corrections into the right commit.

Next: Interactive Rebase