Git & GitHub Course
Git & GitHub
/
Advanced

git rebase

Definition

A command that integrates changes from one branch into another by rewriting the commit history to create a perfectly linear, straight timeline.

Explain Like I'm New

When you use `git merge`, Git creates a messy 'Merge Commit' that ties two diverging branches together. `git rebase` is cleaner. It literally unplugs your feature branch, moves it to the very tip of the `main` branch, and replugs it in. It makes it look like you wrote your feature today, rather than 3 weeks ago.

Real World Example

Keeping a feature branch up-to-date with a fast-moving `main` branch, without cluttering the history with 50 useless 'Merge branch main into feature' commits.

Common Use Cases

  • •Maintaining a clean, linear commit history
  • •Updating stale feature branches

Terminal Output

bash / terminal
# Scenario: You are on 'feature-branch', and 'main' has moved ahead of you. # Step 1: Download latest main $ git checkout main $ git pull origin main # Step 2: Go back to your feature branch $ git checkout feature-branch # Step 3: Rebase your feature onto the tip of main $ git rebase main # Now your feature branch has all the latest code from main, # and your custom commits are neatly stacked on the very top!

Interview Questions

basic

  • Does `git rebase` rewrite commit history?

intermediate

  • What is the 'Golden Rule of Rebase'?

Flash Cards

Question

Rewrite history?

Click to reveal answer
Answer

Yes! It physically changes the cryptographic hashes of your commits. Because of this, it is dangerous.

Question

Golden Rule?

Click to reveal answer
Answer

NEVER rebase a public branch that other developers are working on. Because rebasing changes commit hashes, if you rebase `main` and push it, you will destroy the repository for all your coworkers.