How to Rebase in Git: A Step-by-Step Guide

Rebasing in Git is a powerful tool that lets you rewrite history to create a cleaner, more linear project timeline. While powerful, it must be used carefully—especially in collaborative environments.

In this post, you’ll learn:

  • What rebasing is
  • When to use it
  • How to do it (with commands)
  • Common rebase scenarios

🔄 What Is Git Rebase?

The git rebase command moves or reapplies your commits on top of another branch. It’s often used to:

  • Sync your branch with the latest changes from main or master
  • Clean up commit history before merging
  • Avoid merge commits in feature branches

🆚 Rebase vs Merge: What’s the Difference?

Featuregit mergegit rebase
HistoryCreates a merge commitRewrites history with new commits
Commit LogShows branching pathsAppears as a straight line
Use CasePreserve history, team mergesClean history, personal feature work

✅ Basic Rebase Workflow

Scenario: You’re working on a feature branch and want to rebase it onto the latest main.

🔧 Step-by-Step:

  1. Switch to your feature branch: git checkout feature
  2. Rebase onto main: git rebase main This will move your feature branch commits to the tip of main.
  3. (If conflicts occur) Git will pause and allow you to fix them. After fixing: git add . git rebase --continue
  4. Repeat until rebase is complete.

🔄 Keeping Your Branch Updated

If main has new commits and you want your feature branch to include them:

# From your feature branch
git fetch origin
git rebase origin/main

📤 Rebasing Before a Pull Request

Before opening a PR, rebase your branch to ensure a clean and up-to-date history:

git checkout feature
git fetch origin
git rebase origin/main

Then force push (since rebase rewrites history):

git push --force

⚠️ Only force push to branches you control. Never rebase shared/public branches unless everyone agrees.


🔁 Interactive Rebase

To edit commits, squash, or reorder them:

git rebase -i HEAD~N

Replace N with the number of recent commits you want to rebase.

You’ll see a list like:

pick 1a2b3c First commit
pick 4d5e6f Second commit

Change pick to:

  • squash – combine with the previous commit
  • edit – amend this commit
  • drop – remove the commit

🧠 Summary of Key Commands

TaskCommand
Rebase your branch onto maingit rebase main
Continue after resolving conflictgit rebase --continue
Abort a rebasegit rebase --abort
Interactive rebase (edit commits)git rebase -i HEAD~N
Force push after rebasegit push --force

🚨 Best Practices

  • Never rebase public/shared branches—only rebase your own.
  • Always resolve conflicts carefully during a rebase.
  • Use git log before and after rebasing to understand changes.

🔚 Conclusion

Rebasing is an essential Git skill that helps maintain a clean and linear commit history. Use it to keep your work current, prepare for pull requests, and refine your project timeline.

Sharing Is Caring:

Leave a Comment