← Back to Git Course | Chapter 3: Branching | Lesson 6 of 9

Git rebase Command

Rebasing is like picking up your finished pages and re-gluing them to the end of the newest version of the story, so it looks like you wrote them last in one straight line.
Syntax
bash
git checkout feature_branch
git rebase base_branch
git rebase -i base_branch
git rebase --continue

Basic Rebase

Rebasing takes a sequence of commits and replays them one by one on top of a different base commit, producing a cleaner, linear-looking history compared to the branching structure a merge would leave behind.

Example: Basic Rebase

bash
git checkout feature-x
git rebase main

Continuing Rebase

If replaying a commit during a rebase causes a conflict, Git pauses mid-operation -- you resolve the conflict in the affected files, stage them, then run git rebase --continue to resume replaying the remaining commits.

Example: Continuing Rebase

bash
git add file.txt
git rebase --continue

Interactive Rebase

git rebase -i <commit> opens an interactive editor listing your recent commits, letting you reword messages, squash several commits into one, reorder them, or drop ones you no longer want -- powerful for cleaning up history before sharing it.

Example: Interactive Rebase

bash
git rebase -i HEAD~3

Rebasing Onto Another Branch

git rebase --onto <newbase> <oldbase> <branch> replays only the commits unique to your branch onto a different target, skipping over an intermediate branch entirely -- useful when your branch's actual parent has changed.

Example: Rebasing Onto Another Branch

bash
git rebase --onto main old-feature new-feature

Safe Rebase Practices

Never rebase commits that have already been pushed and that others may have built on -- doing so rewrites history that other people's clones still reference. If you absolutely must push a rebased branch, use --force-with-lease rather than a plain force push, which at least protects against silently overwriting someone else's new commits.

Example: Safe Rebase Practices

bash
git push --force-with-lease
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Rebasing a branch that others have already pulled, which rewrites shared history and causes problems for teammates.
  2. Running git commit during a conflict instead of git add and git rebase --continue.
  3. Rebasing onto the wrong branch, such as running git rebase feature on main instead of git rebase main on feature.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.