notes

git rebase, finally explained for myself

I've used git rebase for years and I still get nervous every time. Writing this so future-me has something to refer to.

What it actually does

Rebase takes a series of commits and replays them on top of a different base. It doesn't merge. It rewrites history so it looks like you started from the new base all along.

The common case

Your feature branch was based on main, but main has moved on. You want your branch to look like it's based on the new main:

git checkout feature
git rebase main

Git replays your feature commits one by one on top of the latest main. If there are conflicts, it stops at each one and waits for you to resolve and run git rebase --continue.

Interactive rebase

The killer feature. Lets you reorder, squash, edit, or drop commits:

git rebase -i HEAD~5

An editor opens with the last 5 commits. Change pick to squash to fold a commit into the one above. Change to reword to fix the message. Delete a line to drop a commit entirely.

The one rule

Never rebase commits that other people have pulled.

Rebase rewrites history. If you rebase commits already on a shared branch, anyone who pulled them will have a bad time. Rebase your own local work freely; rebase shared history never.

When it goes wrong

git rebase --abort at any point puts everything back. Always safe. I use it often.

If you've already finished a rebase and want to undo it: git reflog, find the commit hash from before the rebase, git reset --hard <hash>. Reflog has saved me more times than I can count.