Rebase – Keeping History Clean in Git

01 Min
🔁
Course Under Active Revision Re-visiting

This article belongs to the Git Basics to Advanced course, which is currently being revisited with updated architectural patterns and content. Content may be refined shortly.

Rebasing is the key to a clean and linear commit history.

Instead of merging (which introduces an extra merge commit and diamond-shaped history), rebasing applies your commits one by one on top of the new base.

When we have a feature branch and merge it with master, history can quickly become complicated with extra merge commits:

image.png

What we really want our commit timeline to look like is a single clean line:

image.png

That’s where Git rebase comes in!

1. Interactive Git Rebase Explorer

Step through the interactive timeline below to see how Git lifts feature commits, replays them on top of master’s tip, and fast-forwards master:

Git Rebase Lifecycle

Step 1 of 3: Divergent Feature and Master Branches
1 / 3
main
master
feature
C1
#c1 Base commit
master
C2
#c2 Master patch
F1
#f1 Feature step 1
HEAD → feature
F2
#f2 Feature step 2
$ git log --graph --oneline

Feature branched from C1 with commits F1 and F2. Meanwhile, master progressed to C2.


2. Rebase in Action

Suppose you have a feature1 branch based on an older master commit. Before merging, you want to update it with the latest master changes:

git checkout feature1
git rebase master  # Rebase feature1 onto the latest master

# If conflicts occur, resolve them in files, then:
git add .
git rebase --continue

After rebasing, this is how your codebase appears:

image.png

Now the commits form a single straight line, and you can fast-forward merge feature1 into master:

git checkout master
git merge feature1
git log --all --graph --oneline

Note: In your terminal output, you will see Fast-forward. Because there are no diverging commits on master, the master branch pointer simply advances straight forward to HEAD.


3. The Golden Rule of Rebasing

Never rebase commits that have been pushed to a public, shared branch!

Rebasing creates brand new commits with new SHA hashes. If teammates have already branched off or pulled those original commits, rebasing will cause duplicate commits and painful merge conflicts across your team. Only rebase local, private branches before merging them upstream.