Understanding Git Rebase with Examples and Diagrams

So far, we have explored merges (fast-forward, three-way, squash, and conflict resolution). Now it’s time to understand one of the most powerful Git tools: Rebase.

Rebase allows you to change the base commit of your branch, effectively rewriting history. Let’s walk through an example.


Scenario Setup

Create a new project:

mkdir project6
cd project6
git init

Add a file and make the first commit:

echo "Hello" > hello.txt
git add hello.txt
git commit -m "Initial commit"

Creating a Feature Branch

From the first commit, create a feature branch and make three commits:

git switch -C feature
echo "Feature step 1" > f1.txt
git add f1.txt
git commit -m "Add feature step 1"

echo "Feature step 2" > f2.txt
git add f2.txt
git commit -m "Add feature step 2"

echo "Feature step 3" > f3.txt
git add f3.txt
git commit -m "Add feature step 3"

Now the feature branch is three commits ahead of main.


Adding a Commit on Main

Switch back to main and make another commit:

git switch main
echo "Main branch config" > config.txt
git add config.txt
git commit -m "Add config file in main"

Visualizing History Before Rebase

Run:

git log --oneline --all --graph

Output (simplified):


Here, feature branch diverged from the initial commit (c0), while main moved forward.


Rebasing the Feature Branch

Now rebase feature onto main:

git switch feature
git rebase main

What happens?

  • The parent of feature commits is changed.
  • Git replays the feature commits on top of the latest commit of main.
  • History is rewritten.

Visualizing History After Rebase


Now, it looks as if the feature branch was created from the latest commit of main.


Key Takeaways About Rebase

  • Rebase changes the base commit of your branch.
  • It rewrites history — making your branch appear to come from the latest commit.
  • Very useful if you need the latest work from main before continuing your feature.
  • Safe when you’re working alone.
  • Dangerous in team projects if others are already using the old branch history (it can break their clones).

⚠️ Rule of thumb: Never rebase public/shared branches.


Summary

  • Merge combines histories, preserving all commits.
  • Rebase rewrites history so your branch appears based on the latest commit.
  • Use rebase to keep history linear and clean.
  • Be cautious in team environments — rebasing shared branches can cause problems.

Keep Learning 🚀

👉 Subscribe to Learning Ocean – Subscribers get coupon codes for my courses, early access to blogs and courses, and even exclusive YouTube videos.

👉 My YouTube Channel – More videos, more fun, and lots of learning!

👉 📺 Watch this topic in video form

Stay curious, keep coding, and let’s make learning fun together! 🎉