git rebase takes the commits from your current branch and replays them one by one on top of another branch's latest commit, producing a new, linear sequence of commits instead of merging two diverging histories together.
Key Points: • Rebase rewrites commit hashes as it replays each commit, which is why it should be avoided on commits already pushed and shared with others. • It's most commonly used to update a feature branch with the latest changes from main before opening or merging a pull request. • The resulting history is linear and easier to read through git log or bisect, compared to the extra merge commits that git merge introduces. • Interactive rebase (git rebase -i) additionally lets you reorder, squash, or edit commits along the way, not just replay them unchanged. • Use rebase for personal or not-yet-shared branches to keep history tidy; use merge for shared branches where preserving true history matters more than a clean log.
Example: Before opening a pull request, a developer rebases their feature branch onto the latest main with git rebase main, resulting in a clean, linear set of commits that reviewers can read top to bottom without any merge noise.
Code Example:
git checkout feature-branch
git rebase mainInterview Tip: A concise interview answer is:
"Rebase replays your branch's commits on top of another branch, rewriting their hashes to produce a clean, linear history. I use it to update a feature branch with main before opening a pull request, but I avoid it on commits that are already pushed and shared, where merge is the safer option."