What does `git rebase` do and what is it used for?
Show answer — try answering out loud first
git rebase rewrites history by moving your commits so they start from a new base (usually the tip of another branch). Instead of joining two histories with a merge commit, it "reapplies" your commits one by one on top of the other branch, leaving a linear, clean history.
Imagine you worked on feature starting from an old commit on main, and in the meantime main moved forward. You have two ways to catch up:
- Merge: you join both histories with a merge commit (you end up with a branched history).
- Rebase: you take your commits from
featureand reapply them on top of the latest commit onmain, as if you had started working from there. The result is a straight line, with no merge commit.
"Rewriting history" means Git creates new commits (with different hashes) for your changes, even though the content is the same. That's why rebase is dangerous on shared branches: it changes the identifiers of commits that others might already have.
# I'm on feature and want to catch it up with main using rebase
git switch feature
git rebase main
# Git reapplies my feature commits on top of the latest commit on main
# Output: Successfully rebased and updated refs/heads/feature.
# If a conflict appears during the rebase:
# 1. You resolve it in the file
# 2. git add file
# 3. You continue (do NOT use git commit here)
git rebase --continue
# If you change your mind and want to cancel the whole rebase:
git rebase --abort
# Interactive rebase: reorder, squash, or edit commits
git rebase -i HEAD~3
Rebasing a branch that is already shared/published. Since rebase creates new commits with different hashes, your teammates who had the original commits will end up with divergent histories and painful conflicts. Another mistake: during a rebase with conflicts, trying to finish with git commit instead of git rebase --continue.
"
git rebaserewrites history: it takes my commits and reapplies them on top of a new base, usually the tip of another branch, leaving a linear history with no merge commit. I use it to cleanly catch my branch up withmain, or with-ito reorder and squash commits before a PR. Since it creates new commits with different hashes, I never rebase a branch I've already shared with the team."
During a git rebase main a conflict appears. You resolve it and run git add. Which command do you continue with: git commit or git rebase --continue?
See answer
git rebase --continue. During a rebase, after resolving the conflict and running git add, you continue with git rebase --continue, which reapplies the next commit. You don't use git commit: the rebase manages the commits for you. If you change your mind, git rebase --abort cancels everything and returns to the previous state.