Skip to content
GKgkml.dev
← Learn Git & GitHub

Lesson 5 of 7 · 9 min

Rewriting history: amend, rebase and interactive rebase

Clean up your commits before sharing them, and know exactly where the line is.

The rule

Rewriting produces new commits. Anyone who already has the old ones now has a divergent history, and their next pull creates a mess they did not cause.

So the line is publication: rewrite your own unpushed work as much as you like, and treat anything others have pulled as fixed unless you have agreed otherwise. On a personal feature branch that nobody else tracks, force-with-lease after a rebase is entirely normal.

Interactive rebase
git rebase -i HEAD~4

# pick    keep as is
# reword  keep the change, edit the message
# edit    stop here so you can amend or split
# squash  fold into the previous commit, combine messages
# fixup   fold into the previous commit, discard this message
# drop    remove the commit entirely

# Lines run oldest-first — the opposite of git log. Reordering the
# lines reorders the commits.

Note: Deleting a line drops that commit. That is easy to do by accident, and the reflog is how you undo it.

Amend

git commit --amend replaces the most recent commit with a new one combining it with whatever is staged. Use it for a typo in a message or a file you forgot to include.

It is a rewrite like any other. Amending a pushed commit requires a force push and will disrupt anyone who pulled it.

Merge or rebase for updating a feature branch

Merging main into your branch preserves exactly what happened and never rewrites anything, at the cost of a noisier graph. Rebasing onto main gives a linear history that reviews cleanly, at the cost of new hashes and re-resolving conflicts commit by commit.

The usual team convention: rebase your own feature branch to keep it current, merge it into main with --no-ff so the feature is visible as a unit. Never rebase main itself.

Worth remembering

  • Rewriting always creates new commits with new hashes.
  • Rewrite freely before pushing; after pushing, coordinate or don't.
  • Interactive rebase covers reorder, squash, edit, drop and split.

Test it now

Rebase semantics are among the most-tested medium topics.