Git Rebase

Updated · 13 min read
mediumGit 2.53gitgit-rebaserebase-conflictautostashinterview

Rebasing in Git is a way to move a series of commits to a new starting point, called the base. The git rebase command takes the commits that are on your branch but not on another branch, and replays them, one by one, on top of that other branch. It is used to bring a branch up to date while keeping the history in a straight line, without a merge commit.

A simple comparison: you wrote three pages of notes based on Monday's version of the lecture slides. On Wednesday, the teacher publishes new slides. Instead of keeping your notes on the old slides and stapling the new slides beside them (a merge), you copy your three pages again, one at a time, on top of Wednesday's slides (a rebase). Your notes say the same things, but now they follow the newest version.

What Is a Rebase?

A branch starts from some commit of the branch it was created from. That commit is its base. When the other branch moves on, there are two ways to bring its new commits into your branch:

  • Merge creates a merge commit with two parents, as in "Git Merge". Your commits keep their base.
  • Rebase gives your branch a new base: the newest commit of the other branch. Your commits are re-created on top of it.

Note that rebase doesn't move your commits. It copies them. Each copy has the same changes, author and message as the original, but a new parent, and therefore a new commit ID.

Why Use Rebase?

  • A straight history: the branch's commits come after everything on main, with no merge commits in between, so git log reads like a simple list.
  • Easy reviews: a pull request based on the newest main shows only your changes, and merges as a fast-forward.
  • Early conflicts: you fix conflicts with main in your own branch, one commit at a time, before anyone reviews it.
  • Clean local updates: git pull --rebase (from "Git Pull") avoids small "Merge branch 'main'" commits.

Syntax

Terminal
git rebase [options] <upstream>

<upstream> is the branch (or commit) to rebase onto. Git finds the commits in the current branch that aren't in <upstream>, and replays them on top of it.

OptionDescription
git rebase <branch>It is used to replay the current branch's own commits on top of <branch>.
--continueIt is used to go on after resolving a conflict and running git add.
--skipIt is used to drop the current commit and go on with the next one.
--abortIt is used to stop the rebase and return the branch to how it was before.
--autostashIt is used to stash uncommitted changes before the rebase and restore them after.
-iIt is used to edit the list of commits first (see "Interactive Rebase").
--onto <newbase>It is used to choose a different new base (see "Rebase Onto and Stacked Branches").

Example 1: Rebase a Branch Onto an Updated main

Navika started feature/receipts from main and made two commits. Meanwhile, main got the hostel fee:

Terminal
mkdir fee-tracker
cd fee-tracker
git init --quiet
echo "Fee Tracker" > README.md
echo 'Term 1 fee: $12,000' > fees.txt
git add .
git commit --quiet -m "Add README and the term fee"
git switch --quiet -c feature/receipts
echo "Receipt No. 1" > receipts.txt
git add receipts.txt
git commit --quiet -m "Add receipt numbers"
echo "Print after payment" >> receipts.txt
git commit --quiet -am "Print a receipt after payment"
git switch --quiet main
echo 'Hostel fee: $9,000' >> fees.txt
git commit --quiet -am "Add the hostel fee"
git log --oneline --graph --all
Output
* d9fe232 (HEAD -> main) Add the hostel fee
| * da357cb (feature/receipts) Print a receipt after payment
| * c7de0dd Add receipt numbers
|/
* 4988b51 Add README and the term fee

The feature branch's base is "Add README and the term fee". It doesn't have the hostel fee. Navika rebases it onto main:

Terminal
git switch --quiet feature/receipts
git rebase main
Output
Successfully rebased and updated refs/heads/feature/receipts.
Terminal
git log --oneline --graph --all
Output
* e159c0f (HEAD -> feature/receipts) Print a receipt after payment
* 87c5fc1 Add receipt numbers
* d9fe232 (main) Add the hostel fee
* 4988b51 Add README and the term fee

Explanation:

  1. Git found the two commits on feature/receipts that aren't on main.
  2. It moved the branch to the newest commit of main, "Add the hostel fee".
  3. It replayed the two commits on top, one by one, and moved the branch to the last copy.

The history is now a straight line. Compare the IDs: the two receipt commits have new IDs, because their parent changed. The original commits are no longer on any branch. main itself didn't change: a rebase only moves the current branch.

A rebase replays your commits on a new base

Because the feature branch now contains all of main, merging it into main later is a fast-forward.

Example 2: A Conflict During a Rebase

A conflict happens when a replayed commit changes lines that the new base also changed. Here, Navika's branch and main both change the term fee:

Terminal
git switch --quiet -c feature/fee-update main
sed -i.bak 's/$12,000/$12,500/' fees.txt
rm fees.txt.bak
git commit --quiet -am 'Raise the term 1 fee to $12,500'
echo "Fees are per term." >> README.md
git commit --quiet -am "Say that fees are per term"
git switch --quiet main
sed -i.bak 's/$12,000/$13,000/' fees.txt
rm fees.txt.bak
git commit --quiet -am 'Raise the term 1 fee to $13,000'
git switch --quiet feature/fee-update
git rebase main
Output
Auto-merging fees.txt
CONFLICT (content): Merge conflict in fees.txt
error: could not apply 46b4c78... Raise the term 1 fee to $12,500
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Could not apply 46b4c78... # Raise the term 1 fee to $12,500

The rebase stopped at the first commit, "Raise the term 1 fee to $12,500", because it conflicts with main. The second commit hasn't been replayed yet. git status explains where you are:

Terminal
git status
Output
interactive rebase in progress; onto c9c2ef3
Last command done (1 command done):
   pick 46b4c78 # Raise the term 1 fee to $12,500
Next command to do (1 remaining command):
   pick 440d0f9 # Say that fees are per term
  (use "git rebase --edit-todo" to view and edit)
You are currently rebasing branch 'feature/fee-update' on 'c9c2ef3'.
  (fix conflicts and then run "git rebase --continue")
  (use "git rebase --skip" to skip this patch)
  (use "git rebase --abort" to check out the original branch)
 
Unmerged paths:
  (use "git restore --staged <file>..." to unstage)
  (use "git add <file>..." to mark resolution)
	both modified:   fees.txt
 
no changes added to commit (use "git add" and/or "git commit -a")

The conflict markers are the same as in "Resolving Merge Conflicts". The team decides on $12,500. Navika fixes the file, marks it resolved with git add, and continues:

Terminal
printf 'Term 1 fee: $12,500\nHostel fee: $9,000\n' > fees.txt
git add fees.txt
GIT_EDITOR=true git rebase --continue
Output
[detached HEAD 3a9f501] Raise the term 1 fee to $12,500
 1 file changed, 1 insertion(+), 1 deletion(-)
Successfully rebased and updated refs/heads/feature/fee-update.

Explanation: git rebase --continue commits the resolved copy and replays the remaining commit, which applies cleanly. [detached HEAD ...] appears because, during a rebase, Git works on a detached HEAD and moves the branch only at the end. In your terminal, git rebase --continue opens your editor with the commit message, so you can keep it or change it. Here, GIT_EDITOR=true accepts the message without opening an editor, just for this one command.

Terminal
git log --oneline -3
Output
a7bc3ff (HEAD -> feature/fee-update) Say that fees are per term
3a9f501 Raise the term 1 fee to $12,500
c9c2ef3 (main) Raise the term 1 fee to $13,000

During a conflicted rebase, you have three choices:

CommandDescription
git add <file> then git rebase --continueIt is used to accept your resolution and go on.
git rebase --skipIt is used to drop the commit being replayed, when its change is no longer needed.
git rebase --abortIt is used to cancel the whole rebase. The branch goes back exactly to where it was.

Note that in a rebase, "ours" and "theirs" are swapped compared with a merge. While replaying, Git stands on the new base, so HEAD (ours) is main plus the commits replayed so far, and "theirs" is the commit being replayed, your own work. Keep that in mind before you use git restore --ours or --theirs during a rebase.

Example 3: Uncommitted Changes and --autostash

Git refuses to start a rebase while you have uncommitted changes to tracked files:

Terminal
echo "Draft: discounts" >> README.md
git rebase main
Output
error: cannot rebase: You have unstaged changes.
error: Please commit or stash them.

--autostash stashes the changes, rebases, and restores them, in one step:

Terminal
git rebase --autostash main
Output
Created autostash: f699574
Current branch feature/fee-update is up to date.
Applied autostash.

Here the branch was already up to date with main, so there was nothing to replay, and the stash came straight back. Set git config --global rebase.autoStash true to make this the default.

The Golden Rule

Note that a rebase replaces commits with copies that have new IDs. If other people already have the old commits, because you pushed the branch and they built on it, their history and yours no longer match. So:

After rebasing a branch you had already pushed for yourself (such as your own pull request branch), push with git push --force-with-lease (see "Force Push Safely"). Never rebase main or any other shared branch. The next lesson, "Merge vs Rebase", looks at this choice in detail.

Common Mistakes

Rebasing a shared branch. Teammates' copies break. Rebase only your own unpushed work, or your own branch.

Running git rebase in the wrong direction. git rebase main while on main does nothing useful. Switch to the feature branch first.

Forgetting git add before --continue. Git says the conflict isn't resolved. Add the files first.

Panicking in the middle of a rebase. git rebase --abort always takes you back. And after a finished rebase, git reflog and ORIG_HEAD lead to the old branch.

Pushing a rebased branch without force. The push is rejected, because the branch's history changed. Use --force-with-lease, only on your own branch.

Under the Hood

A rebase is a series of cherry-picks. Git:

  1. Finds the commits to replay: those reachable from your branch but not from <upstream> (the same as git log <upstream>..HEAD).
  2. Saves the branch's current position in ORIG_HEAD.
  3. Detaches HEAD at the tip of <upstream>.
  4. Applies each commit's changes in turn, creating a new commit with the same message, author and author date.
  5. Moves the branch to the last new commit and reattaches HEAD.

The new commits get new IDs because a commit's ID is calculated from its content, including the parent line, and the parent is now different. Commits whose changes are already in <upstream> (for example, because they were cherry-picked there) are recognized and skipped. While a rebase is in progress, its state lives in .git/rebase-merge/, which is how --continue, --skip and --abort know where you are.

Interview Corner

What does git rebase do?

It takes the commits on the current branch that aren't on the target branch, and replays them one by one on top of the target branch, creating new commits with new IDs. The result is a linear history based on the target.

Why do rebased commits get new commit IDs?

A commit ID is a hash of the commit's content, which includes its parent. Replaying a commit on a new base gives it a new parent, so it becomes a new commit with a new ID.

How do you resolve a conflict during a rebase?

Edit the conflicted files, git add them, and run git rebase --continue. Use git rebase --skip to drop the current commit, or git rebase --abort to return to the state before the rebase.

What is the golden rule of rebasing?

Don't rebase commits that others have, such as commits on a shared branch. Rebasing rewrites them, so everyone else's history diverges from yours.

What does rebase.autoStash do?

It makes git rebase stash uncommitted changes before starting and re-apply them after finishing, instead of refusing to run.

Practice

Challenge: catch up again. On main, add Exam fee: $800 to fees.txt and commit. Then rebase feature/receipts onto main again, and print its last three commits.

What does Git print? Before you open the solution, decide whether this rebase conflicts, and whether the receipt commits keep their IDs from Example 1.

Show solution
Terminal
git stash --quiet
git switch --quiet main
echo 'Exam fee: $800' >> fees.txt
git commit --quiet -am "Add the exam fee"
git switch --quiet feature/receipts
git rebase main
Output
Successfully rebased and updated refs/heads/feature/receipts.
Terminal
git log --oneline -3
Output
ab76cda (HEAD -> feature/receipts) Print a receipt after payment
f657502 Add receipt numbers
39b2f3d (main) Add the exam fee

No conflict: the receipt commits change receipts.txt, and main changed fees.txt. But the receipt commits get new IDs again, because their base changed again. (The git stash at the start puts aside the draft README line from Example 3, so the switch to main works.)

Checkpoint. In a practice repository, build a three-commit feature branch, move main on with a commit that conflicts with the second feature commit, and rebase. Resolve the conflict, continue, and compare git log --oneline --graph --all before and after.

Quick check: Git rebase

4 questions
1What does git rebase main do on a feature branch?
2Why do rebased commits get new IDs?
3A rebase stopped with a conflict. After fixing the file, what do you run?
4When should you not rebase?

Key Takeaways

Quick reference

CommandIt is used to
git rebase mainReplay the current branch on main
git rebase --continueGo on after resolving a conflict
git rebase --skipDrop the commit being replayed
git rebase --abortCancel the rebase
git rebase --autostash mainRebase with uncommitted changes
git config --global rebase.autoStash trueAlways autostash
git reset --hard ORIG_HEADUndo a finished rebase right after it

Was this tutorial helpful?

Lesson 54 of 106