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

Git rebase Command

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

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.