Git & GitHub ยท Chapter 18 of 42

git rebase

Rebasing replays your branch's commits on top of another branch, creating a cleaner, linear history instead of a merge commit. It rewrites commit history, so it should be used carefully, especially on shared branches.

A common workflow is rebasing a feature branch onto the latest main before merging, so the history reads as if the feature was built starting from the newest code.

Syntax
git switch feature-branch
git rebase main

Basic rebase

Run `git rebase main` while on your feature branch to replay its commits on top of the latest main branch commits.

Rebase vs merge

Merge preserves exact history with a merge commit. Rebase rewrites history into a straight line, which looks cleaner but changes commit hashes.

Example 1 (bash)
git switch feature-login
git rebase main
Output
Successfully rebased and updated refs/heads/feature-login.

Replays feature-login's commits on top of the latest main branch.

Example 2 (bash)
git rebase --abort

Cancels an in-progress rebase and returns the branch to its state before the rebase started.

Key points

  • Rebase replays commits on top of another branch for a linear history.
  • Rebase rewrites commit hashes, unlike merge.
  • Never rebase commits that have already been pushed and shared with others.
  • git rebase --abort cancels a rebase in progress.
๐Ÿ’ก Note: The golden rule of rebasing: don't rebase commits that other people have already pulled.

๐Ÿ“ Quick Quiz

1. What does git rebase do?

2. What is the 'golden rule' of rebasing?

3. How do you cancel an in-progress rebase?