Rewrite Git commit history cleanly with interactive rebase

Clean up commits with interactive rebase

A feature branch often ends with commits like “WIP”, “fix typo” and “oops, nonce check”. Before the pull request you can turn them into one or two commits that describe the change. git rebase -i rewrites the commits of your branch: you decide which ones to keep, merge, reword or drop.

Problem: A feature branch has five small commits with useless messages, and the reviewer should see one clean commit “Add the plugin settings page”.

Solution: Start git rebase -i on the commit where the branch started, mark the follow-up commits as squash or fixup, write one message, and update the remote branch with git push --force-with-lease.

Squash the branch

git log --oneline main..HEAD
# a1b2c3d oops: nonce check
# d4e5f6a WIP settings page works
# 7a8b9c0 settings page scaffold
# 1d2e3f4 plugin boilerplate

git rebase -i main

Git opens the editor with the oldest commit on top:

pick 1d2e3f4 plugin boilerplate
fixup 7a8b9c0 settings page scaffold
fixup d4e5f6a WIP settings page works
fixup a1b2c3d oops: nonce check

git rebase -i main takes all commits since the branch left main, so you do not have to count them for HEAD~4. After saving, the four commits are one. Change the first pick to reword (or run git commit --amend afterwards) to write a proper message.

The commands in the list

pick    use the commit as it is
reword  use it, but edit the message
edit    stop at this commit to change its files
squash  merge into the previous commit, combine both messages
fixup   merge into the previous commit, drop this message
drop    remove the commit

Lines can also be moved up and down to change the order.

Fixups as you go

git commit --fixup=7a8b9c0       # "fixup! settings page scaffold"
git rebase -i --autosquash main  # the fixup is already placed and marked

Push the rewritten branch

git push --force-with-lease origin feature/settings-page

--force-with-lease refuses to overwrite the remote branch if someone pushed to it after your last fetch. Plain --force would silently delete their commits.

If it goes wrong

git rebase --abort        # during the rebase: back to the state before it
git reflog                # after it: find the old HEAD
git reset --hard HEAD@{5}

NOTE: Rewrite only commits that nobody else has built on: your own feature branch before or during review. Never rebase main or another shared branch. See also essential Git commands.