Git & Command Line Tutorial · Branching and Collaboration · Lesson 15 of 20

Rebasing

Replay your commits on top of the latest main with git rebase for a straight history, squash messy commits with interactive rebase, and know when not to rebase.

Create a free account to save this page, take notes and track your progress. Sign in

Rebase vs merge

git rebase main (run on your feature branch) takes your commits and replays them on top of the latest main, as if you'd started from there. The result is a straight line of history with no merge commit.

  • Merge keeps the true history, including when branches diverged.
  • Rebase rewrites your branch's commits (new hashes) for a cleaner history.

Interactive rebase (git rebase -i HEAD~3) lets you reorder, edit, squash (combine) or reword commits before sharing them: turn "wip", "fix", "fix again" into one clear commit.

The rule: only rebase commits that haven't been shared, or that only you use. Rebasing a branch others have pulled forces them to untangle duplicated commits. After rebasing a pushed feature branch you must git push --force-with-lease.

Rebasing a feature branch and squashing commits
git init -b main --quiet blog && cd blog
echo "post 1" > posts.txt && git add . && git commit -m "First post" --quiet
git switch -c feature/comments --quiet
echo "comments" > comments.txt && git add . && git commit -m "Add comments" --quiet
echo "comment moderation" >> comments.txt && git commit -am "Moderate comments" --quiet
git switch main --quiet
echo "post 2" >> posts.txt && git commit -am "Second post" --quiet

echo "--- before rebase:"
git log --oneline --graph --all
git switch feature/comments --quiet
git rebase main --quiet
echo "--- after rebasing feature/comments onto main:"
git log --oneline --graph --all

git reset --soft HEAD~2 && git commit -m "Add comments with moderation" --quiet   # squash the two commits
echo "--- after squashing:"
git log --oneline

Output

--- before rebase:
* fd7e1bb Moderate comments
* 47b2e3e Add comments
| * 8d7ac03 Second post
|/  
* 5352f00 First post
--- after rebasing feature/comments onto main:
* e9255b9 Moderate comments
* 1673c81 Add comments
* 8d7ac03 Second post
* 5352f00 First post
--- after squashing:
7c762ca Add comments with moderation
8d7ac03 Second post
5352f00 First post

Run this on your computer — see “Get Started” for setup.

Test yourself

When should you avoid rebasing?

  1. Never rebase
  2. When the commits have already been shared and others built on them
  3. When the branch has one commit
  4. When main is ahead
Show answer

Answer: When the commits have already been shared and others built on them

Was this page helpful?