tezvyn:

Git Rebase: Rewriting History for a Cleaner Timeline

AI-drafted, machine-checkedSource: git-scm.comintermediate

Git rebase rewrites history by transplanting your commits onto a new base, creating a clean, linear project history instead of a merge bubble. It's used to catch a feature branch up with `main`. Never rebase a branch others are using; it rewrites history.

WHY IT EXISTS To maintain a clean, linear project history. A standard git merge creates a "merge commit" every time you integrate changes, which can clutter the log with branching and merging lines. Rebasing avoids this by re-applying your commits directly on top of the target branch, as if you had started your work from its latest point.

THE MENTAL MODEL Think of it as "changing the base" of your work. Instead of merging two histories together, you're taking your sequence of changes and pretending you made them on top of a different, more recent starting point. It rewrites your local history to tell a cleaner, more logical story.

HOW IT WORKS When you run git rebase main from your feature branch, Git finds the common ancestor commit. It then saves your unique commits from the feature branch as temporary patches. Next, it fast-forwards your branch to match main. Finally, it applies your saved patches one by one on top of the new branch tip, creating new commits with new SHA-1 hashes for each of your original changes. If a conflict occurs, the process pauses, letting you resolve it before continuing.

WHEN TO USE IT Use rebase to update your local, private feature branch with changes from the main branch. This keeps your branch up-to-date and makes the final merge into main a simple fast-forward. Also, use interactive rebase (git rebase -i) on your local branch to clean up your work before sharing: squash multiple "WIP" commits into one, reword commit messages, or reorder changes for clarity.

WHEN NOT TO USE IT The absolute rule is to never rebase a public branch that other developers have pulled and are working on (like the main or develop branch). Rebasing rewrites history by creating new commits. If you push a rebased branch, it will conflict with the history your teammates have, forcing them into complex and error-prone manual repository fixes. Use git merge for integrating changes on shared branches.

ONE CANONICAL EXAMPLE Your feature branch diverged from main. main has new commits F and G. Your feature has commits B and C. Before: A---F---G (main) and A---B---C (feature). After running git checkout feature and git rebase main, your history becomes a straight line: A---F---G---B'---C' (feature). Your B and C commits are now B' and C', re-applied on top of G.

Read the original → git-scm.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.