How Git Rebase Works: A Clear and Practical Guide

In Git, rebase is a powerful command that allows you to rewrite commit history by moving or combining commits. It’s often used to clean up a feature branch before merging, or to incorporate the latest changes from a main branch without creating a messy commit tree.

In this guide, you’ll learn what git rebase does, when to use it, and how to perform a rebase safely.


🧠 What Is Git Rebase?

git rebase moves or “re-applies” commits from one branch onto another base commit. Unlike merge, which creates a new merge commit, rebase replays your changes on top of another branch, resulting in a linear history.


🔄 Rebase vs. Merge (Quick Comparison)

Featuregit mergegit rebase
Commit historyKeeps all commits, creates a merge commitLinearizes history (no merge commit)
ClarityShows full branch structureCleaner, straight-line history
Use caseCollaborative workflowsClean, private or local workflows

✅ How to Use Git Rebase

Example Scenario

You have a feature branch and want to bring in the latest commits from main.

git checkout feature
git rebase main

This does the following:

  • Rewinds your feature branch to the base of main
  • Applies your feature commits on top of main

🔁 Rebase Workflow: Step-by-Step

  1. Switch to the branch you want to rebase: git checkout feature
  2. Run the rebase command: git rebase main
  3. Resolve conflicts (if any): Git will pause and prompt you to resolve each conflict manually. After fixing, run: git add <resolved-file> git rebase --continue
  4. Repeat until done.

✏️ Interactive Rebase (To Edit Commits)

git rebase -i HEAD~n

This opens an editor where you can:

  • pick commits to keep
  • squash commits to combine
  • reword commit messages
  • drop commits you no longer need

Perfect for cleaning up your commit history before pushing.


⚠️ Rebase Tips and Best Practices

  • Never rebase public/shared branches. It rewrites history, which can confuse collaborators.
  • Always pull with rebase to avoid unnecessary merge commits: git pull --rebase
  • Use --onto for advanced rebasing: git rebase --onto new-base old-base feature

📝 Summary

TaskCommand
Rebase feature onto maingit checkout featuregit rebase main
Resolve conflictFix → git add .git rebase --continue
Abort rebasegit rebase --abort
Interactive rebasegit rebase -i HEAD~n
Pull with rebasegit pull --rebase

🎯 Use Cases for Git Rebase

  • Clean up messy commit history
  • Reapply changes on top of latest main
  • Prepare a feature branch for merge (with --squash)
  • Remove or edit old commits interactively

By mastering git rebase, you gain the ability to shape your commit history exactly how you want it—clean, logical, and easy to read.

Sharing Is Caring:

Leave a Comment