Skip to main content

Rebase

Git rebase is a powerful command that allows you to integrate changes from one branch into another by moving or rewriting commit history. It is an alternative to git merge, but instead of creating a merge commit, it rewrites the commit history to keep it linear.

Why Use Git Rebase?

  • Keeps commit history clean and linear: Instead of multiple merge commits, rebase makes it appear as if all work happened sequentially.

  • Avoids unnecessary merge commits: It moves your feature branch commits on top of the latest commit from the main branch.

  • Useful for integrating changes from remote branches: Before pushing changes, rebasing ensures your branch is up-to-date.

Example

Let's say you are working on a feature branch (feature-branch), and the main branch has received updates. Instead of merging, you decide to use rebase.

main:
A --- B --- C (main)

feature-branch:
\
D --- E (feature-branch)
  • A → B → C are the commits in the main branch.
  • D → E are commits in the feature-branch, which was created from B.

Now, suppose main has received new commits (C), and you want to update your feature-branch with these latest changes.

  1. Switch to feature-branch.
  2. Rebase your branch onto main: git rebase main What happens now:
  • Git moves commits D and E aside.
  • It updates feature-branch with the latest changes from main (i.e., commits C).
  • Then, it reapplies D and E on top of C.
  1. Handling Conflicts: If there are conflicts, Git will pause the rebase and show a message: To resolve, manually fix the conflict in the affected files, use git add to stage teh resolved files. Continue the rebase:
git rebase --continue
  1. Successfully Rebased History
main:
A --- B --- C (main)
\
D' --- E' (feature-branch)

Now, D and E have been reapplied as D' and E' on top of C, keeping history linear.

Differences: Rebase vs Merge

FeatureMergeRebase
Commit HistoryCreates a merge commitKeeps history linear
Commit OrderBranches remain separateCommits appear as if they were created sequentially
Use CasePreserves original historyMakes history cleaner

Commands

  • git rebase <branch> – Rebase your current branch onto another branch.
  • git rebase --interactive <commit> (-i) – Start an interactive rebase for modifying commits.
  • git rebase --continue – Continue rebase after resolving conflicts.
  • git rebase --abort – Abort rebase and return to the original branch state.
  • git rebase --skip – Skip the current conflicting commit and continue rebase.
  • git rebase --onto <new-base> <old-base> <branch> – Rebase a branch onto a different base.
  • git pull --rebase – Fetch changes and rebase instead of merging.